码迷,mamicode.com
首页 > 编程语言 > 详细

java list add的弊病

时间:2015-08-28 17:51:25      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

import java.util.ArrayList;
import java.util.List;
class  t{
    private  int x;
    private  int y;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}
public class Main {

    public static void main(String[] args) {
        int i = 10;
        List<t>list = new ArrayList<>();
        t a = new t();//--------------(1)
        while(i!=0){
           // t a = new t();  --------------------(2)
            a.setX(i);
            a.setY(i+9);
            i--;
            list.add(a);
        }
        for(i= 0 ;i<9;i++){
            System.out.println(i+": "+list.get(i).getX());
        }
    }
}

(1)情况输出

0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
7: 1
8: 1

(2)输出

0: 10
1: 9
2: 8
3: 7
4: 6
5: 5
6: 4
7: 3
8: 2

由此可见,当list循环添加对象时,添加的只是地址,如果地址没有变,数值变了,并没有什么变化。(文档如下 中英对照)

 /**
     * Appends the specified element to the end of this list (optional
     * operation).
     *
     * <p>Lists that support this operation may place limitations on what
     * elements may be added to this list.  In particular, some
     * lists will refuse to add null elements, and others will impose
     * restrictions on the type of elements that may be added.  List
     * classes should clearly specify in their documentation any restrictions
     * on what elements may be added.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     * @throws UnsupportedOperationException if the <tt>add</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and this
     *         list does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this list
     */
    boolean add(E e);

/ **
     *将指定元素添加到此列表的末尾(可选
     *操作)。
     *
     * <p>这是支持该操作的列表可能什么限制
     *元件可被添加到该列表中。特别是,一些
     *列表将拒绝添加null元素,和其他人将施以
     *对可以添加元素的类型限制。名单
     *类应该在其文档明确规定任何限制
     *什么元素可以加入。
     *
     * @参数E元素被添加到这个列表
     * @返回的<tt>真</ TT>(所指定的{@link集合#加})
     * @throws UnsupportedOperationException异常,如果在<tt>添加</ tt>的操作
     *不支持此列表
     * @throws ClassCastException - 如果该类指定的元素
     *不允许它添加到此列表
     * @throws NullPointerException - 如果指定的元素为null,并且此
     *列表不允许null元素
     * @throws IllegalArgumentException - 如果此元素的某些属性
     *不允许它添加到此列表
     * /

版权声明:都是兄弟,请随意转载,请注明兄弟是谁

java list add的弊病

标签:

原文地址:http://blog.csdn.net/u013076044/article/details/48052919

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!