2017-05-31 78 views
0

如何在每次將值「添加」到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

您的輸入與期望輸出的示例? –

回答

7

您可以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

2

您需要其結算前做一個列表的副本:

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

更新:YCF_L的解決方案是沒有必要獲得開銷,並給予額外的工作比我的原因之一顯然是更好GC。

1

attributeList創建一個新的ArrayList對象,當你在largeAttributeList添加attributeList

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

這樣,當你執行attributeList.clear()你清楚只有attributeList而不是在largeAttributeList中添加的列表對象。

2

當你這樣做:

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); 
    } 
}