0

I have a little problem, i hope you could help me solve it.

I have a class called Entity which has several attributes, two of those attributes are the id and the utility:

public class Entity implements Comparable <Entity> {

  int id;
  int utility;

}

Then, i have several Entity objects inside an ArrayList, like this:

ArrayList<Entity> sorted_entities = new ArrayList<Entity>
//added entities

Now, i want to sort the list basing on UTILITY entities. I tried several soluctions like this one which i read here, using a custom comparator:

Collections.sort(sorted_entities, new Comparator<Entity>() {

public int compare(Entity a, Entity b) {
    return a.utility.compareTo(b.utility);
}

});

But on this line:

return a.utility.compareTo(b.utility);

I met the following error: int cannot be dereferenced and i have no idea how fix it. Can you guys help me solve this problem or give another solution? Thx.

Removed
  • 109
  • 3
  • 19
  • Sorry i found several topics but i didn't see that one with the comparator problem. – Removed Dec 15 '15 at 20:48
  • I really wonder why you create a `Comparator`, when your `Entity` already implements `Comparable`. – Tom Dec 15 '15 at 20:55

1 Answers1

1

You have to use the wrapper types:

return Integer.valueOf(a.utility).compareTo(Integer.valueOf(b.utility));

You can actually omit the explicit convert of b.utility to Integer, because it will be autoboxed anyway.

Alternatively (an even better), you can also do:

return Integer.compare(a.utility, b.utility);

where no boxing will be involved.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • Thank you, i used your second code and the error disappeared. But another little problem: Collections.sort(blabla, the code that i posted upside, modified ofc) doesen't order my list, it do nothing. I have to made a sort of call to order the list? Sorry for the idiot question – Removed Dec 16 '15 at 09:56
  • calling `Collections.sort()` with the proper argument should sort your list. No additional work is needed. Try to print the list after the sort and/or debug it. – Konstantin Yovkov Dec 16 '15 at 10:05
  • Ok nothing, problem solved, that helped too much! Thank you kocko! ^^ – Removed Dec 16 '15 at 10:08