2015-09-25 49 views
2

這段代碼引發錯誤 該方法使用從keySet迭代器中檢索的密鑰訪問Map條目的值。在地圖的entrySet上使用迭代器會更有效,以避免Map.get(鍵)查找。 請指導我如何改換性能 - 使用keySet迭代器代替entrySet迭代器的效率低

if (docPropertiesMap != null) { 
     Iterator<String> properties = docPropertiesMap.keySet().iterator(); 
     IDocProperty[] docProperties = new IDocProperty[docPropertiesMap 
       .size()]; 
     int iArrIndex = 0; 

     while (properties.hasNext()) { 
      String strPropName = properties.next(); 
      String[] propValue = docPropertiesMap.get(strPropName); 

      IDocProperty docProperty = (IDocProperty) FDMAFactory 
        .getDataObject("DocProperty"); 
      docProperty.setPropertyName(strPropName); 
      docProperty.setArrPropertyValues(propValue); 
      docProperties[iArrIndex++] = docProperty; 
     } 
     metadata.setArrDocProperties(docProperties); 
     return metadata; 
    } 
+2

請看看類似的問題: http://stackoverflow.com/questions/3870064/performance-considerations-for-keyset -and-entryset-of-map?rq = 1 – vijay

回答

1

這是SonarQube警告FindBugs的距離來。

你可以重寫你的代碼是這樣的:

if (docPropertiesMap != null) { 
    IDocProperty[] docProperties = new IDocProperty[docPropertiesMap.size()]; 
    int iArrIndex = 0; 

    for (Map.Entry<String, String[]> entry : docPropertiesMap.entrySet()) { 
     String strPropName = entry.getKey(); 
     String[] propValue = entry.getValue(); 

     IDocProperty docProperty = (IDocProperty) FDMAFactory.getDataObject("DocProperty"); 
     docProperty.setPropertyName(strPropName); 
     docProperty.setArrPropertyValues(propValue); 
     docProperties[iArrIndex++] = docProperty; 
    } 
    metadata.setArrDocProperties(docProperties); 
    return metadata; 
} 
+0

非常感謝你 – Arun