2017-09-05 80 views
1

我有這樣一個類:複雜性()在枚舉類方法

public enum ReturnCode{ 

Code1(
    "Code1", 
    "Return this code when there is an erreur" 
    ), 

Code2(
    "Code2", 
    "Return this code when everything ok" 
    ); 

ReturnCode(final String code, final String detail) { 
    this.code = code; 
    this.detail = detail; 
} 

private static Map<String, ReturnCode> map = 
     new HashMap<String, ReturnCode>(); 

static { 
    for (ReturnCode returnCode : ReturnCode.values()) { 
     map.put(returnCode.code, returnCode); 
    } 
} 

public static ReturnCode fromValue(String code) { 
    return map.get(code); 
} 

我只是想在複雜性方面知道,是它優於:

public static returnCode fromValue(String code) { 
     for (returnCode returnCode : returnCode.values()) { 
      if (returnCode .code.equals(code)) { 
       return returnCode ; 
      } 
     } 
    } 

因爲它似乎每次我們在第一個方法中調用fromValue時,它會生成一個映射,所以它也是O(n)?

謝謝。

回答

0

地圖是靜態對象。此外,它由靜態代碼塊中的代碼填充。每個類只調用一次靜態代碼塊。沒有理由爲什麼地圖會生成一次以上。

這意味着你的第二個fromValue(),它是O(n),將會比原來的fromValue()慢O(1)的性能。