2

私はFruitモデルクラスを持っています:

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

comparableフルーツクラスにインターフェースを実装し、Collections.sort(list) http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.htmlを使用します

于 2012-05-14T10:35:19.243 に答える
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 に答える
0

コンパレータを使用できます。ドキュメントについては、http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.htmlを参照してください

于 2012-05-14T10:34:29.677 に答える
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 に答える