Hi I am trying to add same object with different property settings. But When Iterate through the List it gives me latest added Setting.
As you can see below is my code.
List<TestObject> list = new ArrayList<TestObject>();
TestObject t= new TestObject();
t.setEmail("[email protected]");
list.add(t);
System.out.println(list.get(0).getEmail());
t.setEmail("The_lawyer99yahoo.com");
list.add(t);
System.out.println(list.get(1).getEmail());
for(TestObject s : list)
{
System.out.println(s.getEmail());
}
Output:
[email protected]
The_lawyer99yahoo.com
The_lawyer99yahoo.com
The_lawyer99yahoo.com
What my doubt is why iteretor is giving latest added Object seting (email) But When I excute this statement System.out.println(list.get(0).getEmail()); its working fine
Why is for loop just keep returning with recently added object ?
Thanks in advance.
Listwill allow you to add the same instance of aObjectmultiple times, so it can "look" like you've added multiple objects when in fact, it's just a bunch of elements pointing to the same object. Use aSetof some kind instead and you will find you only have a single object ;)