Reputation: 1973
I have created this new set and want to add items to the set. But it won't get into the loop. I tried running the program and it would not display in the for loop. I am not sure hwy or how I would change the code for it to work.
Set<Name> names = Sets.newHashSet();
for (Name n : names) {
System.out.println("in the for loop");
n.setName("Tom);
}
Upvotes: 1
Views: 102
Reputation: 692121
Here's what your program does, in English:
Set<Name> names = Sets.newHashSet();
Let's create a new empty set of names, that we'll call "names"
for (Name n : names) {
Let's iterate through all the names present in the empty set we have just created. This obviously is useless, since the set is empty.
System.out.println("in the for loop");
Let's write to the console that we're in the loop. This will never be executed, since the set is empty.
n.setName("Tom);
Let's change the name of the current Name object in the loop. But since the loop is never executed, it will never happen.
Before iterating over elements in a set, add elements to the set:
Name n = new Name("Tom"); // this creates an new object of type Name
names.add(n); // this adds the Name we just created to the set.
// Now the set has 1 element.
If you want to add several names to the set, you can also use a loop, and create and ad a new Name at each iteration:
for (int i = 0; i < 10; i++) {
Name n = new Name("Tom " + i);
names.add(n);
}
// now the set contains 10 elements: Tom 0, Tom 1, ..., Tom 9
Upvotes: 5