简体   繁体   中英

Adding objects to the generic list

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("John1989@gmail.com");
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:

John1989@gmail.com
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.

You're not creating a new object, but simply changing properties of the same object in memory. List will allow you to add the same instance of a Object multiple 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 a Set of some kind instead and you will find you only have a single object ;)

You would need to create a new instance of the TestObject for each new entry, for example...

List<TestObject> list = new ArrayList<TestObject>();
TestObject  t= new TestObject();
t.setEmail("John1989@gmail.com");
list.add(t);
System.out.println(list.get(0).getEmail());

t= new TestObject();
t.setEmail("The_lawyer99yahoo.com");
list.add(t);
System.out.println(list.get(1).getEmail());

for(TestObject s : list)
{
   System.out.println(s.getEmail());
}

This way, the properties are associated with a different instance of the TestObject for each entry

我猜Java只将对对象的引用放入列表中,因此,更改元素的属性也会影响列表内容。

Your problem is called aliasing. When you submit your object t to the container, it's actually interested in the reference of your object. Because of that, the item at position 0 and the one at position 1 are exactly the same, because you stored the same reference at the same object twice instead of two different objects. Thus when you modify t you are actually modifying the sole object created till now, and both the references will show the updated date.

To solve it, simply create a new object and add it to the list by using the following line (as you already do the first time):

t = new TestObject();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM