0

How can I empty the attributeList every time it has "added" the value to largeAttributeList?. I've tried .clear() but then the largeAttributeList loses all the values.

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);
        }
    }
1
  • Examples of your input vs expected output? Commented May 31, 2017 at 10:47

4 Answers 4

7

You can inisialize your array inside your loop :

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

This would initialize it at every round of the for. While he only wants to empty it when added so I would move your suggestion into the if(current.equals("Identifier")){. That way it would always be a new one once he added it, wouldn't it?
2

You need to make a copy of a list before its clearing:

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

Update: YCF_L solution is obviously better than my one cause there is no necessity to obtain overhead and give additional work for GC.

Comments

2

When you do:

largeAttributeList.add(attributeList);

You are not making a copy of attributeList, but adding its reference to largeAttributeList. I think the best solution would be to re-initialize attributeList in the loop:

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

Comments

1

Create a new ArrayList object for attributeList when you add attributeList in largeAttributeList :

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

In this way when you execute attributeList.clear() you clear only attributeList and not the list object added in largeAttributeList.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.