如何排序根据两个PARAMATERS在Java中比较对象的列表? [英] How to sort a list of objects according to two paramaters to compare at Java?
问题描述
我有一个这样的类:
public class Zern extends Something{
private int costA;
private int costB;
public int getcostA() {
return costA;
}
public void setcostA(int costA) {
this.costA = costA;
}
public int getcostB() {
return costB;
}
public void setcostB(int costB) {
this.costB = costB;
}
}
我有认为那种对象列表:
I have a list that holds that kind of objects:
private List<Zern> zerns = new ArrayList<Zern>(MAX_ZERN_SIZE);
我将新对象添加到我的名单,但是我总是想按照成本有一个有序的列表,如果在列表中的一个对象,它与我的对象相同的成本,我想补充我想补充一点,根据其costB对象。
I will add new objects to my list however I always want to have a ordered list according to cost a and if there is an object at list which has the same cost with my object that I want to add I want to add that object according to their costB.
我的意思是:的
I mean:
Index of objects at list 0 1 2 3 4 5
CostA 10 15 22 22 25 36
CostB 26 12 17 19 23 44
If I want to add an object that has a costA 22 and costB 18,
it will locate at index 3.
我怎样才能有效地做到这一点(因为我将一个对象添加到排序列表中,这样就意味着我可以使用二进制搜索 - 如果可能的话我希望根据,要找到一个解决方案)是比较或类似的东西?
How can I do it effectively (because I will add an object to a sorted list so it means that I can use binary search - if it is possible I want to find a solution according to that) with Comparator or something like that?
推荐答案
使用 Collections.sort
与以下比较:
Collections.sort(zerns, new Comparator<Zern>() {
@Override
public int compare(Zern z1, Zern z2) {
if (z1.getcostA() == z2.getcostA()) {
return z1.getcostB() == z2.getcostB() ? 0 :
z1.getcostB() < z2.getcostB() ? -1 : 1;
} else {
return z1.getcostA() < z2.getcostA() ? -1 : 1;
}
}
});
更新:如果您不需要您的项目索引访问,你可能需要使用一个有序集合实现从首位使用自定义比较:
Update: If you do not need indexed access to your items you may want to use a sorted set implementation from the first place with a custom comparator:
TreeSet<Zern> zerns = new TreeSet<Zern>(new Comparator<Zern>() {
@Override
public int compare(Zern z1, Zern z2) {
if (z1.getcostA() == z2.getcostA()) {
return z1.getcostB() == z2.getcostB() ? 0 :
z1.getcostB() < z2.getcostB() ? -1 : 1;
} else {
return z1.getcostA() < z2.getcostA() ? -1 : 1;
}
}
});
现在对象可以被添加,你的设置将始终保持排序(注:我添加了一个构造函数和toString你Zern类):
Now objects can be added and your set will always remain sorted (note: I added a constructor and toString to your Zern class):
zerns.add(new Zern(10, 26));
System.out.println(zerns); // => [(10,26)]
zerns.add(new Zern(22, 19));
System.out.println(zerns); // => [(10,26), (22,19)]
zerns.add(new Zern(22, 17));
System.out.println(zerns); // => [(10,26), (22,17), (22,19)]
zerns.add(new Zern(15, 12));
System.out.println(zerns); // => [(10,26), (15,12), (22,17), (22,19)]
您可以删除项目
zerns.remove(new Zern(22, 17));
System.out.println(zerns); // => [(10,26), (15,12), (22,19)]
或删除最坏的成本项目
zerns.remove(zerns.last());
System.out.println(zerns); // => [(10,26), (15,12)]
或通过
System.out.println(zerns.first()); // => (10,26)
这篇关于如何排序根据两个PARAMATERS在Java中比较对象的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!