2016-01-16 28 views
-2

我有一個名爲Car的類,該類具有如id,名稱,價格,顏色和大小等屬性。當我創建一個對象時,對於顏色和大小,我想要一個列表來從中選擇屬性值。我不希望用戶寫「黑」或「小」,我想在應用程序的某個地方找到它們。從列表中選擇屬性值-java

Car c1 = new Car(1, "Super Car", 152.5, "black", "small"); 

有沒有人可以幫助我呢?

+0

也許你的意思是你想使用枚舉的? –

+0

您可以爲此創建枚舉('Color','Size') – Andrew

+0

請更好地定義您的用例,因爲例如它不清楚「user」是什麼意思。這是使用您的API或使用您的應用程序的最終用戶的開發人員嗎? –

回答

0

然後,您應該有可供用戶選擇的值的列表。以下是顏色的例子(只是一個簡單的例子,沒有去太深成Java構建了每個方案):

List<String> color = new ArrayList<String>(); 
color.add("black"); 
color.add("white"); 
// etc 

Car c1 = new Car(1, "SuperCar", 152.5, color.get(userSelectedOptionIndex), "smal"); 

這裏,userSelectedOptionIndex應該是用戶選擇的GUI選項的索引。

0

1)你可以使用一個類通過簡單的字符串來保存您的常量:

public final class Constants { 

    private Constants() { 
     // restrict instantiation 
    } 

    public static final String COLOR_BLACK = "black"; 
    public static final String COLOR_WHITE = "white"; 

    public static final String SIZE_SMALL = "small"; 
    public static final String SIZE_LARGE = "large"; 
} 

用法:

Car c1 = new Car(1, "Super Car", 152.5, Constants.COLOR_BLACK, Constants.SIZE_SMALL) 

2)另一種方法是使用常量類枚舉:

public final class Constants { 

    private Constants() { 
     // restrict instantiation 
    } 

    public static enum Color { White, Black }; 
    public static enum Size { Small, Large }; 
} 

用法:

Car c1 = new Car(1, "Super Car", 152.5, Constants.Color.White, Constants.Size.Small) 

3)但更好的方法(更多OOP批准)是單獨定義枚舉和丟棄常量類完全

public enum Color { 
    White, 
    Black 
} 

public enum Size { 
    Small, 
    Large 
} 

用法:

Car c1 = new Car(1, "Super Car", 152.5, Color.White, Size.Small) 

,倘若你,如果你有一個GUI元素,用戶應該從中選擇valuse,可以使用這些枚舉值創建一個Array或List,然後填充您的GUI元素:

JavaFx 8示例:

Color[] values = Color.values(); 
ComboBox<Color> comboBox = new ComboBox<>(); 
comboBox.getItems().addAll(values); 

後來得到選擇的值:

Color selectedColor = comboBox.getValue();