0

How do I create an object with an arraylist and then when I clear the arraylist I want the value to still be inside the object.

for (int i = 0; i < attribute.getLength(); i++) {
    String current = attribute.item(i).getTextContent();
    if(current.equals("Identifier")){
        String hyperlink = list.get(count).hyperlink;
        String title = list.get(count).title;
        String identifier = list.get(count).identifier;
        ItemAndAttributeObject object = new ItemAndAttributeObject(hyperlink, identifier,  title, attributeList);
        objectList.add(object);
        count++;
        attributeList.clear();
    }
    else{
        attributeList.add(current);
    }
}

When I run this code all the ItemAndAttributeObject attributes are empty. How do I keep the value in the objects?

This is how my class, creating the objects looks like

public class ItemAndAttributeObject {
    String hyperlink;
    String identifier;
    String title;
    ArrayList<String> attributes;

    public ItemAndAttributeObject(String hyperlink, String identifier, String title, ArrayList<String> attributes) {
        this.hyperlink = hyperlink;
        this.identifier = identifier;
        this.title = title;
        this.attributes = attributes;
    }
}

I want is to create an object with an arraylist of values and then clear the array for the next iteration in the loop.

Sergey
  • 176
  • 2
  • 12
LinusJS
  • 43
  • 3
  • So you create some objects put them in an array list in some scope, clear the arraylist in that scope and want the objects to still be here? Why?? This question kind of smells like an [X/Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) –  May 30 '17 at 10:45

1 Answers1

1

Don't keep using and clearing the same ArrayList. Create a new ArrayList each time.

Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21