Java 7源码分析第9篇 - List集合基于链表的实现(二)

2014-11-24 07:14:37 · 作者: · 浏览: 1
set(2, 33); for(Number i:l){ System.out.println(i);// 1 2 33 4 5 } 修改l的值list中的值不会受到影响,再举个例子:

String[] x={"a","c"};
		String[] y={"m","n"};
		LinkedList
  
    list=new LinkedList<>();
		list.add(x);
		list.add(y);
		
		
		LinkedList
   
     l=(LinkedList
    
     ) list.clone(); l.get(1)[1]="ttttt"; System.out.println(list.get(1)[1]);
    
   
  

这时候打印出的值为ttt,也就是修改克隆后的引用值,原值也会被修改,这时候就要用深度克隆了。如果细心且阅读过源代码的人就会发现,有些方法克隆链表元素的方法其实和clone方法是一样的,如下:

  public Object[] toArray() {
        Object[] result = new Object[size];
        int i = 0;
        for (Node
  
    x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }
  
 public 
  
    T[] toArray(T[] a) {
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Node
   
     x = first; x != null; x = x.next) result[i++] = x.item; if (a.length > size) a[size] = null; return a; }