问题
I have a list of objects of type A, and I have to order it for a field of A, which is of type String.
public class A{
public String field1;
public Integer field2;
...
}
If I had to order for the int field would have done so:
Collections.sort(listOfA, new Comparator<A>() {
public int compare(A p1, A p2) {
return p1.field2 - p2.field2);
}
});
But unfortunately need to order by the field of type String.
How can I do this?
回答1:
public int compare(A p1, A p2) {
return p1.field2.compareTo( p2.field2) );
}
回答2:
Alternatively your class could implement interface Comparable, like this
public class A implements Comparable<A> {
public String field1;
public Integer flied2;
public int compareTo(A o) {
return this.field1.compareTo(o.field1);
}
}
Which would allow you to
Collections.sort(listofA);
Which IMO is preferable/cleaner if A's are always sorted by field1.
回答3:
You could use String compareTo
来源:https://stackoverflow.com/questions/6890006/comparator-using-a-string-field-of-my-class-for-comparison