-1

さまざまなオブジェクト「Equipo」を含むarraylistがあり、さまざまな並べ替えパラメーターで並べ替える必要があります

public class Equipo {

private String nombre;
private int puntos;
private int cantidadPartidosGanados;
private int golesDiferencia;
private int golesAnotados;
private int golesEnContra;

if int puntos; is equals sort by int cantidadPartidosGanados; それが等しい場合は、int golesDiferencia で並べ替えます。それが等しい場合は、int golesAnotados で並べ替えます。それが等しい場合は、int golesEnContra で並べ替えます。それが等しい場合は、文字列の名前で並べ替えます。

どうもありがとうございます!!!

4

3 に答える 3

1

Comparableインターフェイスを実装するため、このメソッドをクラスに追加する必要があります。

int compareTo(T o) {
    if (this.puntos > o.puntos)
        return 1;
    else if (this.puntos < o.puntos)
        return -1;
    else
        if (this.cantidadPartidosGanados > o.cantidadPartidosGanados)
            return 1;
        else if (this.cantidadPartidosGanados < o.cantidadPartidosGanados)
            return -1;
        else
          // and so on
}

次に Collections クラスでsort静的メソッドを呼び出すと、リストがソートされます。

于 2013-10-03T15:12:24.957 に答える
0

でソートするにはComparator、匿名の実装を に提供しCollections.sort()ます。

Collections.sort(list, new Comparator<Equipo>() {
    public int compare(Equipo a, Equipo b) {
        if (a.getPuntos() != b.getPuntos())
            return a.getPuntos() - b.getPuntos();
        if (a.getCantidadPartidosGanados() != b.getCantidadPartidosGanados())
            return a.getCantidadPartidosGanados() - b.getCantidadPartidosGanados();
        // etc for other attributes in order of preference, finishing with
        return a.getNombre().compareTo(b.getNombre());
    }
});
于 2013-10-03T15:15:25.470 に答える
0

他の回答とは異なり、私は教育的アプローチを採用しているため、少なくとも適用している概念に対処できます。

(インターフェースcompareToを実装する場合) と同じ原理に基づく作業の両方。最初の要素が 2 番目の要素よりも小さい場合は int より小さい値を返し、最初の要素が 2 番目の要素よりも大きい場合、またはそれらが等しい場合は上の int を返します。ComparableComparator000

Comparatorは、順序付け基準を簡単に切り替える方法を提供し、提供されたコンパレータに基づいて複数の方法でコレクションを並べ替えることができます。

オブジェクトを定義したらComparator、 に動作を与える必要があります。これは、前に説明した基準に従って をcompare返します。intクラス内のフィールド間の優先順位を考えると、Equipoフィールドごとに比較を行い、等しい場合は次のフィールドに切り替える必要があります。擬似コードでは、次のようになります。

If equipo1.field1 != equipo2.field1
    compare the fields returning 1 or -1
Else
    If equipo1.field2 != equipo2.field2
        compare the fields returning 1 or -1
    Else
        ...

最終的に、すべてのフィールドが等しい場合は、 を返す必要があります0

プリミティブ型 (つまりString) を扱っていないときは、いつでもそのオブジェクト独自のcompareToメソッドを使用できることに注意してください。比較結果が を返す場合、2 つのオブジェクトが等しいことがわかります0

于 2013-10-03T15:25:20.657 に答える