0
class People {
  int height;
  int weight;
}

List<People> list = new ArrayList<People> ();

我想以字段“高度”为键对列表进行排序。

我可以使用任何预定义的方法吗?如何将高度设置为我的关键?

4

3 回答 3

1

Create a Comparator that takes a key and sorts it by that field

Also See

于 2013-08-03T18:52:16.253 回答
0

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.)

于 2013-08-03T18:54:11.383 回答
0

-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);
于 2013-08-03T18:55:20.810 回答