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

java的引用传值的小问题,谁来帮个忙
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的改变而改变,有什么办法吗?

------解决方案--------------------
Integer i = new Integer(0);
ArrayList state = new ArrayList();
state.add(i);
ArrayList next = new ArrayList();
next.addAll(state);
state.clear();
------解决方案--------------------
调用clone方法,生成对象的副本,改变副本不会影响原对象,所以这样就可以了
------解决方案--------------------


next=state 是把state 的地址给了 next 引用传递
next.addAll(state); 是把state里的值用迭代器赋给 next 是值传递
------解决方案--------------------
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());
}