0

This is sort of a duplicate of this question, however I'm looking for a bit more ELI5 explanation of the "mutable keys" and "buckets" in the answers.

Here is my code that I'm having trouble understanding:

HashSet<Object> set = new HashSet<Object>();
    set.add(1); set.add(2); set.add(3);

    for(Object i : set)
        if(i.equals(1)) {
            i = 1337;
            System.out.println("FOUND"); 
        }

    for(Object i : set) System.out.println(i);

output:

FOUND

1

2

3

Why does this not print out 1337, 2, 3 instead?

Same question goes for removing objects.

EDIT:

This does what I want but I'm fairly certain its not the correct way to go about it:

for(Object i : set)
        if(i.equals(1)) {
            set.remove(i);
            set.add(1337);
            break;
        }
Community
  • 1
  • 1
  • This is all about not being able to make reference assignments within a for-each loop, and has nothing to do with mutable vs. non-mutable keys. The i variable is a temporary limited scope variable, and changing its assignment will have no effect on the contents of the collection being iterated over. – Hovercraft Full Of Eels May 05 '16 at 04:24
  • @HovercraftFullOfEels realizing this was a very stupid question... – 2ARSJcdocuyVu7LfjUnB May 05 '16 at 04:25

2 Answers2

3

You are handling primitives here. What you do in for loop is you copy value from Set to i and then you do some stuff with it. Now, i is completely new variable and you changed its value, not in Set. Therefore, Set is unchanged. So, you must remove it from Set and then put new value, making this OK:

for(Object i : set)
        if(i.equals(1)) {
            set.remove(i);
            set.add(1337);
            break;
        }

Same thing will happen if you have objects, you will have new pointer, not the same object, but two pointers pointing to same place, so you would delete one pointer, but one in the Set will remain, so GC will not delete the object, until pointer in Set is deleted (therefore, no pointers points to the object).

Adnan Isajbegovic
  • 2,227
  • 17
  • 27
0

When you do a set.remove(i) & set.add(i) it would work since you are performing the operation on the set.

But when you do i=1337 you are just assigning a value to the variable i and not performing any set operation.

Ani Menon
  • 27,209
  • 16
  • 105
  • 126