3


私はこのクラスを持っています:

public class Friend {

private String name;
private String location;
private String temp;
private String humidity;

public String getTemp() {
    return temp;
}

public void setTemp(String temp) {
    this.temp = temp;
}

public String getHumidity() {
    return humidity;
}

public void setHumidity(String humidity) {
    this.humidity = humidity;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}


public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}
}

ユーザー入力に基づいて、名前、場所、温度、湿度に基づいてリストを並べ替えたいと思います。
編集:ユーザーは、並べ替えを実行する必要があるデータ メンバーを指定します。
これを行う最も簡単な方法は何ですか?
ありがとうございました。

4

3 に答える 3

6

それらを 4 つの異なる基準で並べ替えたいので、Comparable を実装しても意味がありません。この場合、並べ替えパラメータごとに異なるコンパレータを作成することがあります。ただし、名前など、最も論理的な並べ替えフィールドには Comparable を実装できます。それ以外の場合は、コンパレーターが最適です。

public class FriendNameComparator extends Comparator<Friend> {

    // assuming both are non-null for code simplicity; you may wish to change that
    public int compare(Friend f1, Friend f2) {
        return f1.getName().compareTo(f2.getName());
    }
}

public class FriendLocationComparator extends Comparator<Friend> {

    // assuming both are non-null for code simplicity; you may wish to change that
    public int compare(Friend f1, Friend f2) {
        return f1.getLocation().compareTo(f2.getLocation());
    }
}

// and so forth

次に、Collections ユーティリティ クラスの sort 関数を使用して、指定されたコンパレータで並べ替えることができます。

Collections.sort(friendsList, new FriendNameComparator()); // sorts by name
Collections.sort(friendsList, new FriendLocationComparator()); // sorts by location
// etc
于 2012-05-10T05:43:14.170 に答える
5

Java にはCollections.sort(List, Comparator)、同じタイプの 2 つのオブジェクトが与えられた場合に、どちらが前に並べられるかを決定するカスタム Comparator を指定して、オブジェクトの (汎用化された) List をソートするという静的関数があります。

あなたの仕事は、引数とユーザー指定の並べ替え順序に基づいてオブジェクトを並べ替えるComparatorを作成する関数を作成することです。例えば:

public Comparator<Friend> getComparator(final String sortBy) {
  if ("name".equals(sortBy)) {
    return new Comparator<Friend>() {
      @Override int compare(Friend f1, Friend f2) 
        return f1.getName().compareTo(f2.getName());
      }
    };
  } else if ("location".equals(sortBy)) {
    return new Comparator<Friend>() {
      @Override int compare(Friend f1, Friend f2) 
        return f1.getLocation().compareTo(f2.getLocation());
      }
    };
  } else if ("temp".equals(sortBy)) {
    // ...
  } else {
    throw new IllegalArgumentException("invalid sort field '" + sortBy + "'");
  }
}
于 2012-05-10T05:37:12.130 に答える
1
List list=new ArrayList();

If else if を各基準に使用します。

if(location ){
        Collections.sort(list, new Comparator () {
             public int compare(YourObject o1, YourObject o2) {
                    return o1.getLocation().compareTo(o2.getLocation());
                }

        });

    }

    } else if(temp ){

    ........
    }
    .......
于 2012-05-10T05:40:12.803 に答える