【Java】列挙型 / enum型 ~応用編 / Enumのソート ~

サンプル

 * Enumを逆順でソートさせる(もっとスマートにやりたいが)

SignalType

* Enum
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public enum SignalType {
  None(-2),
  Red(-1),
  Yellow(0),
  Green(1);

  public static final int DESCENDENT = -1;
  private int value;

  private SignalType(int value) {
    this.value = value;
  }

  public int getValue() {
    return this.value;
  }

  /** ★ここがポイント. */
  public static void sort(List<SignalType> list) {
    Collections.sort(list, new Comparator<SignalType>() {
      @Override
      public int compare(SignalType source, SignalType distination) {
        int sortOrderOfSource = source.ordinal();
        int sortOrderOfDistination = distination.ordinal();
        int returnValue;
        if (sortOrderOfSource > sortOrderOfDistination) {
          returnValue = 1;
        } else if (sortOrderOfSource == sortOrderOfDistination) {
          returnValue = 0;
        } else {
          returnValue = -1;
        }
        return returnValue * DESCENDENT;
      }
    });
  }
}

Main.java

* 呼び出し側
import java.util.ArrayList;
import java.util.List;

public class Main {

  public static void main(String[] args) {
    List<SignalType> list = new ArrayList<SignalType>() {
      private static final long serialVersionUID = 1L;
      {
        add(SignalType.Red);
        add(SignalType.Green);
        add(SignalType.Yellow);
      }
    };

    System.out.println("Before sorting");
    for (SignalType type : list) {
      System.out.println(type);
    }

    System.out.println();

    System.out.println("After sorting");
    SignalType.sort(list);
    for (SignalType type : list) {
      System.out.println(type);
    }
  }
}

出力結果

Before sorting
Red
Green
Yellow

After sorting
Green
Yellow
Red


関連記事

列挙型 / enum型 ~基本編~

http://blogs.yahoo.co.jp/dk521123/32503689.html

列挙型 / enum型 ~応用編 / EnumMap / EnumSet ~

http://blogs.yahoo.co.jp/dk521123/34469119.html