I have an Iterable<MyRecord> records . I iterate over the records like below and add it to a LinkedList as shown below.
for (MyRecord record: records){
sortedList.addLast(record);
}
My iterable has 3 records, all with different values. But in the end although sortedList contains 3 records, ALL THREE ARE THE SAME!!!. How come?
When I printed out the memory location, it’s the same for all 3. What am I doing wrong?
Actually your comment reveals the missing link to why this is going wrong. You’re using this in a Hadoop mapper or reducer. The trick with Hadoop is that it reuses the objects you’re getting in, so that it goes easy on the garbage collector. What you thus have to do is make a copy of each of the objects in your source iterable (the
MyRecords), and add those to your LinkedList.