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

实现方法的比较
Java code

public class People {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


实现一:
Java code

public class Test {
    public static void main(String args[]) {
        List<People> list = new ArrayList<People>();
        List<People> list2 = new ArrayList<People>();
        People people1 = null;
        for (int i = 0; i < 5; i++) {
            people1 = new People();
            people1.setAge(i);
            list.add(people1);
        }
        
        People people2 = null;
        for(int j = 0;j < list.size();j++){
            people2 = list.get(j);
            people2.setAge(j+10);
            list2.add(people2);
        }
    }
}


实现二:
Java code

public class Test {
    public static void main(String args[]) {
        List<People> list = new ArrayList<People>();
        List<People> list2 = new ArrayList<People>();
        People people1 = null;
        for (int i = 0; i < 5; i++) {
            people1 = new People();
            people1.setAge(i);
            list.add(people1);
        }
        
        for(int j = 0;j < list.size();j++){
            People people2 = list.get(j);
            people2.setAge(j+10);
            list2.add(people2);
        }
    }
}



问题:
1、两个实现中list2的结果相同吗?为什么?
2、people2的声明哪种好呢?为什么?
3、建议使用哪种实现?

------解决方案--------------------
上面那种好点吧, 不过拉出来声明 性能应该影响不大吧
------解决方案--------------------
1、结果是相同的。
2、楼主不用纠结变理在循环外还是内声明有什么大的性能区别。所以让代码更清晰,表达更准确上讲,第二种更合适。个人观点。
------解决方案--------------------
肯定是第一种好了 第二个太浪费了
------解决方案--------------------
List<People> list = new ArrayList<People>();
List<People> list2 = new ArrayList<People>();
for (int i = 0; i < 5; i++) {
People people1 = new People();
people1.setAge(i);
list.add(people1);
}

for(int j = 0;j < list.size();j++){
list.get(j).setAge(j+10);
list2.add(list.get(j));
}

------解决方案--------------------
第一种指向同一堆空间,第二种在堆中重新创建了新对象吧