-3
下面的代碼片段表示基於名稱如何優化下面的代碼片段?
public static List<String> LANGUAGES = Arrays.asList("js", "java", "html");
public static List<String> LIBRARIES = Arrays.asList("jquery", "ember");
public static List<String> BROWSERS = Arrays.asList("chrome", "safari", "mozilla");
public static List<String> MAIL = Arrays.asList("gmail", "yahoo");
public static List<String> EDITORS = Arrays.asList("vim", "vi", "notepad");
public static getType(String name) {
String type = null;
if(LANGUAGES.contains(name)) {
type = "languages";
} else if(LIBRARIES.contains(name)) {
type = "libraries";
} else if(BROWSERS.contains(name)) {
type = "browsers";
} Else if (MAIL. contains (name)) {
type = "mail";
}else if(EDITORS.contains(name)) {
type = "editors";
}
return type
}
的嘗試與switch語句相同思想的類型。但是交換機不提供選項來檢查Java中的list.contains。
有什麼方法可以更好地寫上面的代碼片段嗎?因爲隨着添加的新類型,getType方法不斷增加。
提示:一'地圖'可以包含一整套的規則:如果一個關鍵是像'vi',值例如'editors'。一次查找可能就足夠了。 –
9000
注意,如果你只是檢查你的容器上的會員資格,使用'Set'或'Collection'。 – IceArdor
你不能初始化那樣的列表 – GurV