class People {
int height;
int weight;
}
List<People> list = new ArrayList<People> ();
我想以字段“高度”为键对列表进行排序。
我可以使用任何预定义的方法吗?如何将高度设置为我的关键?
class People {
int height;
int weight;
}
List<People> list = new ArrayList<People> ();
我想以字段“高度”为键对列表进行排序。
我可以使用任何预定义的方法吗?如何将高度设置为我的关键?
Create a Comparator
that takes a key and sorts it by that field
Also See
You could make your class implement Comparable<People>
, which creates what's called a natural order, but it doesn't seem intuitive that people are always "more" or "less" based on height. A better approach is probably to create a Comparator
, which you can then use with Collections.sort
to sort the list.
(As a note: It's customary in Java for the class name be the singular of what the class represents, so in your case, it would be more legible to name it Person
instead.)
-In order to put some objects into a specific order usually it is recommended to use a Set from Java Collection Framework.And than u have 2 options:
Implement in the same class Comparable
and override the method compareTo
.
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
Implement in a new class the interface Comparator
and override the compare
method.
http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
In your case using Lists you can still do these too and than call the method .sort()
From Collections
.
class HightSort implements Comparator<People > {
public int compare(People one, People two) {
return one.hight-two.hight;
}
}
Collections.sort(list);