JavaにおけるEnumの実用化の列挙

2893 ワード

Wwwwei転載オリジナルの出典を明記してください.ありがとうございます.
Java列挙7つの一般的な使い方
Java列挙7つの一般的な使い方
例を挙げる
需要
りんご、バナナ、梨の3種類の果物があるとします.同じ果物をランダムに選択し、選択した結果情報を印刷します.
構想
このような多分岐構造に対して、私たちは習慣的に番号を使う方法で、3種類の果物をそれぞれ1,2,3に番号をつけます.果物との対応関係を番号で完成させる.
定数の使用方法
定数は通常public static finalと定義し、果物番号を定義します.次のように主関数を記述します.
package main;

import java.util.Random;

public class ConstantMain {
    public static final int APPLE = 1;
    public static final int BANANA = 2;
    public static final int PEAR = 3;

    public static void main(String[] args) {
        //       1-3        
        int type = new Random().nextInt(3) + 1;
        //            
        switch (type) {
        case APPLE:
            //       ,      
            System.out.println("      ,      ");
            break;
        case BANANA:
            //       ,      
            System.out.println("      ,      ");
            break;
        case PEAR:
            //      ,      
            System.out.println("     ,      ");
            break;
        }
    }

}

列挙の使用方法
1.フルーツ列挙類FruitEnumの作成
package enums;

import java.util.Arrays;

/**
 *      
 *
 * @author Wwwwei
 *
 */
public enum FruitEnum {
    APPLE(1, "  "), BANANA(2, "  "), PEAR(3, " ");

    private Integer type;//     
    private String description;//     

    public Integer getType() {
        return type;
    }

    public String getDescription() {
        return description;
    }

    private FruitEnum(Integer type, String description) {
        this.type = type;
        this.description = description;
    }

    /**
     *             
     *
     * @param type
     *                
     * @return
     */
    public static FruitEnum getInstance(Integer type) {
        return Arrays.asList(values()).stream().filter(item -> type != null && item.getType().equals(type)).findFirst()
                .orElse(null);
    }
}

2.主関数の作成
package main;

import java.util.Random;

import enums.FruitEnum;

public class Main {

    public static void main(String[] args) {
        //       1-3        
        Integer type = new Random().nextInt(3) + 1;
        //               
        FruitEnum fruit = FruitEnum.getInstance(type);
        //       
        System.out.println("       :" + fruit.getType() + "
:" + fruit.getDescription()); // switch (fruit) { case APPLE: // , System.out.println(" , "); break; case BANANA: // , System.out.println(" , "); break; case PEAR: // , System.out.println(" , "); break; } } }