I am working in RMI and I have different servers ( class ), I want to store objects from these classes in arraylist, then I want to sort them by shared methode that return some intger number.
3 Answers
Assuming these objects are of type Foo which does not implement Comparable<Foo> but does have a method public int getBar(), you can pass your own Comparator<Foo> to Collections#sort() like so:
List<Foo> foos = /* whatever */;
Collections.sort(foos, new Comparator<Foo> () {
@Override
public int compare(Foo a, Foo b) {
return Integer.compare(a.getBar(), b.getBar());
}
});
Note that Integer#compare(int, int) is only since Java 7. If you're using anything older, use this implementation instead:
public int compare(Foo a, Foo b) {
int x = a.getBar();
int y = b.getBar();
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Comments
Assume that shared method is public Integer sharedMethod() then do the sorting as below:
List<SharedClass> list = new ArraList<SharedClass>();
....
//Sorting here
Collections.sort(list, new Comparator<SharedClass>(){
@Override
public int compare(SharedClass sc1, SharedClasssc2){
return sc1.sharedMethod().compareTo(sc1.sharedMethod());
}
});
If it is returns int then use Integer.compare method (Java7) as below:
//Sorting here
Collections.sort(list, new Comparator<SharedClass>(){
@Override
public int compare(SharedClass sc1, SharedClasssc2){
return Integer.compare(sc1.sharedMethod(), sc1.sharedMethod());
}
});
If using Java Version below 7, then:
//Sorting here
Collections.sort(list, new Comparator<SharedClass>(){
@Override
public int compare(SharedClass sc1, SharedClasssc2){
int value1 = sc1.sharedMethod();
int value2 = sc1.sharedMethod();
//return 1, if value1 is greater,-1 if smaller and 0 if equal to value2.
return (value1 < value2) ? -1 : ((value1 > value2) ? 1 : 0);
}
});
3 Comments
bowmore
Note that every object in java already has a method that return an int : hashCode(), so we might as well use that.
Yogendra Singh
@user1886012 It depends which method, attribute you want to use in sorting. As per OP, he/she wants to sort based on a shared method which returns integer.
bowmore
You are correct, if he only wants the list to quickly find entries he could use hashCode. If the order is somehow semantically relevant, then hashCode is probably not a good option. (and I apologize for only now updating my user name appearance)