性能 - 使用 keySet 迭代器而不是 entrySet 迭代器的效率低下
Performance - Inefficient use of keySet iterator instead of entrySet iterator
这段代码报错
此方法使用从 keySet 迭代器检索到的键访问 Map 条目的值。在映射的 entrySet 上使用迭代器会更有效,以避免 Map.get(key) 查找。
请指导我如何改写它
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;
}
这是来自 FindBugs 的 SonarQube 警告。
您可以这样重写代码:
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;
}
这段代码报错 此方法使用从 keySet 迭代器检索到的键访问 Map 条目的值。在映射的 entrySet 上使用迭代器会更有效,以避免 Map.get(key) 查找。 请指导我如何改写它
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;
}
这是来自 FindBugs 的 SonarQube 警告。
您可以这样重写代码:
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;
}