排序不同类型的对象的列表 [英] sort a list of different type of objects
问题描述
我有一个包含不同类型对象的对象列表,但是所有对象中都有一个属性。
列表包含Field类,Button类,Page类等的对象,但是所有属性中的一个属性是共同的,即sequence_no&
我想根据sequence_no对此列表进行排序。
I have a list of objects which contains different types of objects but a single property is common among all. list contains objects of Field class, Button Class, Page class etc but one property is common among all i.e. "sequence_no" & I want to sort this list on the basis of "sequence_no".
推荐答案
我建议创建一个界面,类似可序列
,方法 getSequenceNo()
。
I'd suggest creating an interface, something like "Sequenceable
" with a method getSequenceNo()
.
public interface Sequenceable {
int getSequenceNo();
}
您的字段
, 按钮
,页面
类应该实现此接口和 getSequenceNo()
方法将返回 sequence_no
。
Your Field
, Button
, Page
classes should implement this interface and the getSequenceNo()
method will return your sequence_no
.
然后你可以实现自己的比较器
并使用此比较器排序。
Then you can implement your own Comparator
and sort using this comparator.
例如,您的比较器将如下所示:
For example, your comparator will look like:
class MyComparator implements Comparator<Sequenceable> {
@Override
public int compare(Sequenceable o1, Sequenceable o2) {
return o2.getSequenceNo() - o1.getSequenceNo();
}
}
然后你可以用以下方式排序:
Then you can sort with:
Collections.sort(list, new MyComparator());
这篇关于排序不同类型的对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!