2

我有一个水果模型类:

public class Fruit{
   private String name;
   private String color;

   public Fruit(String name, color){
     this.name = name;
     this.color = color;
   }
   public getName(){
      return name;
   }
   public getColor(){
      return color;
   }
}

然后,我创建了一个列表fruits

List<Fruit> fruits = new ArrayList<Fruit>();

fruits.add(new Fruit("Orange","orange"));
fruits.add(new Fruit("Strawberry","red"));
fruits.add(new Fruit("Apple","green"));
fruits.add(new Fruit("Banana","yellow"));

现在,我想根据水果名称按字母顺序fruits对元素进行排序。如何有效地对水果列表进行排序?

4

6 回答 6

3

您可以使用Collections.sort(),定义一个Comparator. 例如:

Collections.sort(
    fruits,
    new Comparator<Fruit>()
    {
        public int compare(Fruit f1, Fruit f2)
        {
            // Ignore case for alphabetic ordering.
            return f1.getName().compareToIgnoreCase(f2.getName());
        }
    });
于 2012-05-14T10:33:40.273 回答
2

使用以下

Collections.sort(fruits);

public class Fruit implements Comparable {

    public int compareTo(Object o) {            
        Fruit f = (Fruit) o;
        return this.getName().compareTo(f.getName());
    }

}
于 2012-05-14T10:33:38.093 回答
1

在fruit类上实现comparable接口,使用Collections.sort(list) http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

于 2012-05-14T10:35:19.243 回答
0
public class Fruit implements Comparable<Fruit> {
{
   public int compareTo(Fruit f) {
       if (this.Name == f.Name)
           return 0;
       else if (this.Name > f.Name)
           return 1;
       else
           return -1;
    }
}

像这样使用它:

Collections.sort(fruits);
于 2012-05-14T10:37:25.703 回答
0

您可以使用比较器。有关文档,请查看 http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

于 2012-05-14T10:34:29.677 回答
0
public Comparator<Fruit> fruitComparator = new Comparator<Fruit>() {
        @Override
        public int compare(Fruit f1, Fruit f2) {

            return f1.getName().compareTo(f2.getName());
        }
    };

接着:

Collections.sort(fruits, fruitComparator );
于 2012-05-14T10:43:42.207 回答