Buszman Buszman - 2 months ago 8
Java Question

collections.sort doesn't work for custom objects

I'm trying to sort my List but this one doesn't work. Method collections.sort() does nothing.

public boolean schedule(){
List<Task> keys = new ArrayList<Task>(g.tasks.keySet());
for(int i = 0; i<keys.size();i++){
System.out.println(keys.get(i).getSize());
}
Collections.sort(keys);
for(int i = 0; i<keys.size();i++){
System.out.println(keys.get(i).getSize());
}
return true;
}


and this is my compareTo() method in Task class:

public int compareTo(Task t1) {
Integer csize = new Integer(t1.size);
int cmp = csize.compareTo(t1.size);

return cmp;
}


What is wrong in this method?

Answer

collections.sort doesn't work for custom objects

Sure it does, but it won't in your case because your compareTo method is broken. You're comparing t1's size to itself, not to the size of this

You've got:

public int compareTo(Task t1) {
    Integer csize = new Integer(t1.size);  // get t1's size
    int cmp = csize.compareTo(t1.size);  // ???? compare with t1's size ???

    return cmp;
}

You need to change it to something like:

public int compareTo(Task t1) {
    return Integer.compare(this.size, t1.size);
}

So now you're comparing the size of the parameter with the size of the current object.

Comments