清空循环中的数组列表

问题描述:

如何在每次将值“添加”到largeAttributeList?时清空attributeList。我试过.clear(),但是然后largeAttributeList失去了所有的值。清空循环中的数组列表

ArrayList<String> attributeList = new ArrayList<String>(); 
ArrayList<ArrayList<String>> largeAttributeList = new 
ArrayList<ArrayList<String>>(); 

for (int i = 0; i < attribute.getLength(); i++) { 
     String current = attribute.item(i).getTextContent(); 
     if(current.equals("Identifier")){ 
      largeAttributeList.add(attributeList); 
     } 
     else{ 
      attributeList.add(current); 
     } 
    } 
+0

您的输入与期望输出的示例? –

您可以inisialize你的阵列的循环中:

.... 
ArrayList<String> attributeList; 
for (int i = 0; i < attribute.getLength(); i++) { 
    String current = attribute.item(i).getTextContent(); 
    if (current.equals("Identifier")) { 
     largeAttributeList.add(attributeList); 
     attributeList = new ArrayList<>();//<<<------------- 
    } else { 
     attributeList.add(current); 
    } 

} 
+0

这会在for的每一轮初始化它。虽然他只想在添加时清空它,所以我会将你的建议转移到if(current.equals(“Identifier”)){'。这样,一旦他添加了它,它将永远是一个新的,不是吗? – Nico

您需要其结算前做一个列表的副本:

largeAttributeList.add(new ArrayList<>(attributeList)); 

更新:YCF_L的解决方案是没有必要获得开销,并给予额外的工作比我的原因之一显然是更好GC。

attributeList创建一个新的ArrayList对象,当你在largeAttributeList添加attributeList

largeAttributeList.add(new ArrayList<String>(attributeList)); 

这样,当你执行attributeList.clear()你清楚只有attributeList而不是在largeAttributeList中添加的列表对象。

当你这样做:

largeAttributeList.add(attributeList); 

你最好不要让AttributeList中的一个副本,但增加其参考largeAttributeList。我认为最好的解决方案是重新初始化循环中的attributeList:

List<List<String>> identifierAttributes = new ArrayList<List<String>>(); 
List<String> attributes = new ArrayList<String>(); 
for (int i = 0; i < attribute.getLength(); i++) {   
    String current = attribute.item(i).getTextContent(); 
    if(current.equals("Identifier")){ 
     identifierAttributes.add(attributes); 
     attributes = new ArrayList<String>(); 
    } 
    else { 
     attributes.add(current); 
    } 
}