Question

Im calling collections.sort on an array list of objects of class appointment but it wont sort nothing happens

This is how im calling the collections sort

 ArrayList<appointment> listoffappointments = new ArrayList<appointment>();

 //then everytime on button click user adds a new appointment after setting the following code is executed 
{
 Calendar calendar1 = Calendar.getInstance();                
 calendar1.set(mYear, mMonth, mDay, temphour, tempmin);
 appointment tempppt = new appointment(c2,tempstring1);
 listoffappointments.add(tempppt);
 Collections.sort(listoffappointments);
}

Here is the class can someone find the issue thanks

import java.util.Calendar;

public class appointment  implements Comparable<appointment> {

Calendar time;
String Text;
public appointment(Calendar tempc, String temptext) {
    Text = temptext;
    time = tempc;
}

public void settext(String text)
{
    Text = text;
}
public String gettext()
{
    return Text;
}
public String toString() {
    return Text;
}
public Long gettimeofappt()
{
    return time.getTimeInMillis();

}

@Override
public int compareTo(appointment o) {
     return (this.gettimeofappt() < o.gettimeofappt() ) ? -1: (this.gettimeofappt() > o.gettimeofappt() ) ? 1:0 ;  

}


}
Was it helpful?

Solution

you are returning a Long object, Change your compareTo like:

@Override
public int compareTo(appointment o) {
     return this.gettimeofappt().compareTo(o.gettimeofappt() );

}

Long.compareTo compares two Long objects numerically, and Retunrs:

the value 0 if this Long is equal to the argument Long; a value less than 0 if this Long is numerically less than the argument Long; and a value greater than 0 if this Long is numerically greater than the argument Long (signed comparison).

OTHER TIPS

Try this:

Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareToIgnoreCase(s2);
        }
    });

Look at Sorting ArrayList (String ArrayList and custom class)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top