枚舉代替switch並實現和switch同級別O(1)時間複雜度獲取名稱值
當然啦你要是試過switch和hashmap的速度,你就會知道switch真的快,如果你把switch改爲if else,那你又覺得以後只用if else了,hhhh。沒有最強只有最合適,需要性能只寫if else,爲了開發效率則擇優選擇。
最近邊做邊玩,看着一個新功能要每個方法寫一個switch心生不爽,就給他列巴列巴,看着已經使用了枚舉類型,乾脆一不做二不休,把枚舉搞一搞,說來也巧,枚舉搞switch很簡單。數組就行,如果有字符串那就加個哈希。自己寫唄。
我希望通過輸入的類型(輸入的類型是數字,數字與實際含義通過指定規則對應)直接獲取到指定的規則名稱。代碼如下
最簡單且通用的實現,就是循環遍歷了
/**
* 公告類型:1-公告1;2-公告2;3-公告3;4-公告4
* */
@AllArgsConstructor @Getter
public enum Notice_type{
ONE("公告1",1),TWO("公告2",2),THREE("公告3",3),FORE("公告4",4);
private final String noticeTypeName;
private final Integer value;
/** O(n)獲取封公告類型名稱
* @param type
* @return
*/
public static Notice_type get(int type){
for (Notice_type p: Notice_type.values()) {
if(type == p.value){
return p;
}
}
return null;
}
}
之後就是極致的數組O(1)了
/**
* 公告類型:1-公告1;2-公告2;3-公告3;4-公告4
* */
@AllArgsConstructor @Getter
public enum Notice_type{
ONE("公告1",1),TWO("公告2",2),THREE("公告3",3),FORE("公告4",4);
private final String noticeTypeName;
private final Integer value;
/** O(1)獲取封公告類型名稱 極致效率,但方法不通用,維護成本高
* @param value
* @return
*/
public static String get(int value){
//改到極致則僅能用於此方法
if (value > 4 || value < 0) {
return null;
}
String[] name = {"公告1","公告2","公告3","公告4"};
return name[value-1];
}
}
將名稱寫入數組,通過下標對應,模仿hash實現思路,我這裏只需要value-1這樣簡單的hash規則,複雜的對應規則就要自己實現嘍。