例如:我有一个人类数组:
Human{
private int eyeColor;
private int hairColor;
private int height;
}我想按多个权重对数组进行排序:
眼睛的颜色是最有价值的(越高越好),其次是身高,最后是头发颜色。
等。
假设所有的整数都在0-10的范围内,我考虑为Human entity:创建一个"rank“字段,然后将其乘以以下逻辑:
rank+= 10000 * eyeColor;
rank+= 1000 * height;
rank+= 100 * hairColor;之后只需按等级排序。
我觉得这是一种原始的按权重排序的方法(如果它是对的)。有没有更优雅的方法来解决这个问题呢?
发布于 2013-08-15 15:41:59
也许我的回答过于关注实现细节了。你的问题是,是否有更优雅的方法来解决这个问题?我拒绝了。基本上,您必须将一个具有3个整数的对象映射到一个单独的整数,以便稍后进行比较。
如果您的类中将有更多的属性,我建议您可以制作一些更通用的代码版本,其中每个属性由一个属性和一个相应的权重组成。通过这种方式,您可以创建compareTo方法的更通用形式。但不要过早地进行优化。
我建议像这样实现Comparable接口:
public Human(int eyeColor, int hairColor, int height) {
this.eyeColor = eyeColor;
this.hairColor = hairColor;
this.height = height;
}
public static void main(String[] args) {
List<Human> humans = new ArrayList<Human>();
humans.add(new Human(20, 10, 5));
humans.add(new Human(50, 50, 2));
Collections.sort(humans);
for(Human human : humans) {
System.out.println(human);
}
}
@Override
public int compareTo(Human o) {
int thisRank = 10000 * eyeColor;
thisRank += 1000 * height;
thisRank += 100 * hairColor;
int otherRank = 10000 * o.eyeColor;
otherRank += 1000 * o.height;
otherRank += 100 * o.hairColor;
return thisRank - otherRank;
}https://stackoverflow.com/questions/18248164
复制相似问题