如何根据两个参数对对象列表进行排序以在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;
}
}
我有一个包含此类对象的列表:
private List<Zern> zerns = new ArrayList<Zern>(MAX_ZERN_SIZE);
我会将新对象添加到我的列表中,但是我总是希望根据成本 a 有一个有序列表,并且列表中是否有一个对象具有与我要添加的对象的成本相同我想根据其成本 B 添加该对象。
我的意思是:
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.
我怎样才能有效地做到这一点(因为我将一个对象添加到排序列表中,所以这意味着我可以使用二分搜索 - 如果可能的话,我想用 Comparator 或类似的东西找到一个解决方案?
I have a class like that:
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);
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
Collections.sort
与以下比较器一起使用:更新: 如果您不需要对项目进行索引访问,您可能希望从一开始就使用排序集实现和自定义比较器:
现在可以添加对象,并且您的集合将始终保持排序(注意:我向您的 Zern 类添加了构造函数和 toString):
您可以删除项目
或删除最差成本项目
或通过以下方式获取最佳成本项目
Use
Collections.sort
with the following comparator: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:
Now objects can be added and your set will always remain sorted (note: I added a constructor and toString to your Zern class):
You can remove an item
or remove the worst cost item
or get the best cost item via
只需比较第一个标准即可。如果匹配,则比较第二个条件:
Just compare the first criteria. If they match, compare the second criteria: