保存List中对象的相同值

时间:2014-11-02 09:27:52

标签: java

/ *我创建了一个Employee类和一个实例变量A,并且我已经覆盖了toString()方法。

I created a test class in which I create a `List` of `Employee` type. After creating `Employee` object `obj`, I initialized `A` variable using `obj.A=10` and added this obj into the `List` with `add(obj)`. In the next line I initialized `obj.A=13` and added into the list with `add(obj)`. This way I added a  different value to the list. 

When I iterateover the List to display it, I see only the last value multiple times. Why is that? What should I do if I want to save different values using a single object and a single instance variable?*/


package com.swt;

/**
 *
 * @author RISHI
 */
public class Employee {
    public int a;
    Employee ()
    {}

    public int getA() {
        return a;
    }

    public void setA(int a)
 {

        this.a = a;
    }

    @Override

    public String toString() 
{

        return "Employee{" + "a=" + a + '}';
    }

}


package com.swt;

import java.util.ArrayList;
import java.util.List;
public class EmployeTest {

    public static void main(String[] args) 
{
            List<Employee> al=new ArrayList<Employee>();

            Employee obj=new Employee();

            obj.a=10;

            al.add(obj);

            obj.a=13;

            al.add(obj);

            obj.a=15;`enter code here`

            al.add(obj);

            for(Employee e:al)
{




                System.out.println("your list iteam value is"+e);
            }
    }

2 个答案:

答案 0 :(得分:1)

您将多次添加相同的Employee对象到列表中。这就是为什么列表中的所有Employee具有相同数据的原因(因为它们是同一个对象)。

每次要将Employee添加到列表之前,都必须创建一个新实例。

List<Employee> emps = new ArrayList<Employee>();
Employee emp = new Employee (); // create first employee
emp.A = 10;
emps.add(emp); // add first employee
emp = new Employee(); // create second employee
emp.A = 13;
emps.add(emp); // add second employee

答案 1 :(得分:0)

您只创建了一个实例。您对其进行了更改并一次又一次地插入到列表中。因为它们都是同一个对象,所以它们都获得了最新的价值。