0

I am trying to add an object of class Document to an arraylist in a loop. the problem is that every time the object changes, the prevous contents of the list changes too

here's my Document class:

public class Document {
    public Map<String, Double> tokens;
    public String category;    
}

and I have the list dataset:

List<Document> dataset = new ArrayList<Document>();

I read all the tokens of a document from a file to a map named counts. then do as follows

doc = new Document();
doc.tokens = counts;
doc.category=sampleCategory;
dataset.add(doc);

counts.clear();

but every time i read a new doc, the contents of dataset changes to the values of new doc. So how can I add the doc by value, not by reference?

S_M
  • 290
  • 3
  • 18

2 Answers2

2

Looks like you're adding the same 'counts' object to all of your Document instances. Instead of counts.clear(), assign counts to a new instance of the corresponding type:

counts = new HashMap<String, Double>
yole
  • 92,896
  • 20
  • 260
  • 197
0

You are reusing the same instances for counts and sampleCategory everytime, so any modification will modify the rest.

You should create a new objects each time, and then assign into the new Document.