Integer i = new Integer(0);
ArrayList  next = new ArrayList();
ArrayList  state = new ArrayList();
state.add(i);next = state;
state.clear();next这时是指state的地址吗?
执行state.clear()以后next也被清空了,我想让state的值赋给next,这样next就不随着state的改变而改变,有什么办法吗?

解决方案 »

  1.   

    Integer i = new Integer(0);
    ArrayList  state = new ArrayList();
    state.add(i);
    ArrayList  next = new ArrayList();
    next.addAll(state);
    state.clear();
      

  2.   

    调用clone方法,生成对象的副本,改变副本不会影响原对象,所以这样就可以了
      

  3.   

    next=state  是把state  的地址给了 next  引用传递
    next.addAll(state);  是把state里的值用迭代器赋给 next 是值传递
      

  4.   

    public void copyVal()
    {
    Integer i = new Integer(0);
    ArrayList state = new ArrayList();
    ArrayList next ;
    state.add(i);
    next= (ArrayList) state.clone();
    System.out.println("state:"+state.size());
    System.out.println("next:"+next.size());
    state.clear();
    System.out.println("state:"+state.size());
    System.out.println("next:"+next.size());
    }