praks5432
praks5432

Reputation: 7792

Does a HashSet make an internal copy of added Objects?

Let's say I have a function that is recursive and is like this

public void someRecur(List<Integer>someList){
  if(someBreakCondition)
    Set.add(someList);
  for(int i = 0; i < someLen ; i++){
    someList.add(someInt);
    someRecur(someList);
    someList.remove(someInt);
   }
}

Does the remove affect the list that has been put into the set? What should I do to give the set an actual copy of the list?

Upvotes: 1

Views: 1545

Answers (5)

Marko Topolnik
Marko Topolnik

Reputation: 200226

I must warn you that you must not change the object after you have put it into the set—and that's what you are doing in your code: you add the list to the set and then update it afterwards. This messes up with its hashcode and breaks the HashSet. Maybe you don't even need a Set there, but another list.

You can add a safe copy of the list to the set easily by either cloning (as suggested elsewhere), or by explicitly constructing a new ArrayList(someList).

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213351

Does the remove affect the list that has been put into the set?

Yes, it will be affected. What you put into the Set is not the actual list, but a reference to that list. So, when the list is modified, all the reference pointing to that list will see the changes.

What should I do to give the set an actual copy of the list?

For, that you can create a new list, and add all the elements from the original list to that and add it to your Set -

List<Integer> newList = new ArrayList<Integer>();
newList.addAll(someList);
set.addAll(newList);

Or, simply: -

set.addAll(new ArrayList<Integer>(someList));

Upvotes: 3

assylias
assylias

Reputation: 328765

The set will hold a reference to the list - so there is only one list. You can add/remove items to/from the original list directly or use the list that is in the set: it will have the same effect.

Upvotes: 1

Jesper
Jesper

Reputation: 206926

No, HashSet does not make a copy of objects that you add to it.

Upvotes: 2

duffymo
duffymo

Reputation: 308958

You don't put objects into a map; you add references to objects that live out on the heap.

Java data structures hold references to objects, not the objects themselves. If you remove a reference from a data structure, other objects may still have a copy of that reference.

If two objects hold references to a mutable object, then each one will see changes made by the other. (This is why thread safety is important.)

When no one refers to an object on the heap, it's eligible for GC.

Upvotes: 3

Related Questions