我在 RMI 中工作,我有不同的服务器(类),我想将这些类中的对象存储在数组列表中,然后我想通过返回一些整数的共享方法对它们进行排序。
最佳答案
假设这些对象的类型为 Foo
它没有实现 Comparable<Foo>
但确实有一个方法public int getBar()
,您可以通过自己的 Comparator<Foo>
至 Collections#sort()
像这样:
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());
}
});
请注意 Integer#compare(int, int)
is only since Java 7 。如果您使用的是旧版本,请改用此实现:
public int compare(Foo a, Foo b) {
int x = a.getBar();
int y = b.getBar();
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
关于java - 对来自不同类的对象的数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13779490/