在Java中的属性值排序的对象的ArrayList [英] Sorting an object ArrayList by an attribute value in Java
问题描述
我 ArrayList的僵尸
,其中填充有名为僵尸
的对象。 僵尸
的属性健康
, X
,是
。 僵尸
,这是设置的我怎么会以升序排序的数组,使用属性 X
最初具有随机值?
I have ArrayList zombie
, which is populated with an object called Zombie
. Zombie
has the attributes health
, x
, y
. How would I sort the array in ascending order, using the attribute x
of Zombie
, which is set to initially have random values?
我已经找到了一个可能的<一个href=\"http://stackoverflow.com/questions/4310014/sort-an-arraylist-base-on-multiple-attributes\">solution我的问题,但我不知道答案的语法。并解释说,答案可能会有帮助,也。
I have already found a possible solution to my problem, but I do not understand the syntax of the answer. Explaining that answer may help, also.
推荐答案
您想要使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\"><$c$c>Collections.sort$c$c>用自定义<连词href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html\"><$c$c>Comparator$c$c>.
Collections.sort(list, new Comparator<Zombie>() {
@Override
public int compare(Zombie z1, Zombie z2) {
if (z1.x() > z2.x())
return 1;
if (z1.x() < z2.x())
return -1;
return 0;
}
});
从本质上讲,比较
是如何表示的列表应该通过它的比较
方法进行排序的关键。随着比较
上面,我们考虑 Z1
是大于的比 Z2
如果 Z1
具有较高的 X
值(我们通过返回显示此 1
)。在此基础上,我们的排序列表
。
Essentially, a Comparator
is a key that signifies how a list should be ordered via its compare
method. With the Comparator
above, we consider z1
to be greater than z2
if z1
has the higher x
value (and we show this by returning 1
). Based on this, we sort list
.
这篇关于在Java中的属性值排序的对象的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!