日期:2014-05-20  浏览次数:20704 次

关于java.util.List的一个问题

POJO类:
Java code

public class People {
    public String name;
    public String sex;

    public People(String name, String sex) {

        this.name = name;
        this.sex = sex;
    }
}



业务逻辑:
Java code

import java.util.ArrayList;
import java.util.List;

public class Service {

    public List<People> getList(List<People> list) {

        List<People> l1 = new ArrayList<People>();
        People p = new People("123", "男");
        for (People p1 : list) {

            p.name = p1.name;
            p.sex = p1.sex;
            System.out.println(p.name + " " + p.sex);
            l1.add(p);
        }
        return l1;
    }
}




测试代码:
Java code

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        List<People> l = new ArrayList<People>();

        l.add(new People("aaa", "男"));
        l.add(new People("bbb", "女"));

        List<People> result = new Service().getList(l);

        for (People p : result) {
            System.out.println(p.name + " " + p.sex);
        }
    }



为什么控制台会输出:

bbb 女
bbb 女

而不是

aaa 男
bbb 女

呢?

------解决方案--------------------
Java code

//参考:当修改p属性后,list中的元素属性也会变化
import java.util.*;

class People 
{
    public String name;
    public String sex;
    public People(String name, String sex) 
    {
        this.name = name;
        this.sex = sex;
    }
    public String toString()
    {
        return this.name+"-"+this.sex;    
    }
}

class Test
{
    public static void main(String []args)
    {
        People p = new People("aa","AA");
        List<People> list = new ArrayList<People>();
        list.add(p);
        System.out.println(list);
        
        p.name = "bb";//注意:当修改p属性后,list中的元素属性也会变化
        list.add(p);
        System.out.println(list);
    }
}

------解决方案--------------------
People p = new People("123", "男");这句代码放到for循环中,就可以得到你想要的结果了,至于什么原因,给你点提示,对象与引用的问题,两个引用指向同一个对象,那么这两个引用就有相同数据了。仔细想想。。
------解决方案--------------------
探讨
关键在这部分代码
People p = new People("123", "男");
for (People p1 : list) {

p.name = p1.name;
p.sex = p1.sex;
System.out.println(p.name + " " + p.sex);
l1.add(p);
}
程序最终使用的是getList方法返……