比较器使用我的类的String字段进行比较? [英] Comparator using a String field of my class for comparison?
本文介绍了比较器使用我的类的String字段进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类型为A的对象列表,并且必须对它的类型为String的A字段进行排序.
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;
...
}
如果我必须订购int字段,则会这样做:
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);
}
});
但不幸的是,需要按String类型的字段进行排序.
But unfortunately need to order by the field of type String.
我该怎么做?
推荐答案
public int compare(A p1, A p2) {
return p1.field2.compareTo( p2.field2) );
}
这篇关于比较器使用我的类的String字段进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文