Java:向量加法函数是否很浅?
使用“添加”功能将对象添加到向量时,是浅拷贝还是深拷贝?Java:向量加法函数是否很浅?,java,vector,deep-copy,shallow-copy,Java,Vector,Deep Copy,Shallow Copy,使用“添加”功能将对象添加到向量时,是浅拷贝还是深拷贝? 如果它是浅的,则意味着如果您更改向量中的对象,您将更改对象的原始副本?向量仅包含指向您添加的对象的指针,它不会创建“深”副本。(Java中没有通用的机制来创建任意对象的“深层”副本,因此库集合很难提供此类功能!)它是浅层副本,实际上根本不是副本,列表中引用的是同一对象。如果要传递深度副本,请使用implemente iface和方法clone(),或者可以使用副本构造函数。例如,它是浅层的 Vector<MyObj> vict
如果它是浅的,则意味着如果您更改向量中的对象,您将更改对象的原始副本?向量仅包含指向您添加的对象的指针,它不会创建“深”副本。(Java中没有通用的机制来创建任意对象的“深层”副本,因此库集合很难提供此类功能!)它是浅层副本,实际上根本不是副本,列表中引用的是同一对象。如果要传递深度副本,请使用implemente iface和方法clone(),或者可以使用副本构造函数。例如,它是浅层的
Vector<MyObj> victor = new Vector<MyObj>();
MyObj foo = new MyObj();
MyObj bar = new MyObj();
foo.setValue(5);
bar.setValue(6);
victor.add(foo);
victor.add(bar);
foo.setValue(3);
victor.get(1).setValue(7);
// output: 3, even though it went into the vector as 5
System.out.println(victor.get(0).getValue());
// output: 7, even though we changed the value of the vector 'object'
System.out.println(bar.getValue());
向量victor=新向量();
MyObj foo=新的MyObj();
MyObj条=新的MyObj();
foo.设定值(5);
bar.设定值(6);
添加(foo);
添加(bar);
foo.setValue(3);
get(1)、setValue(7);
//输出:3,即使它作为5进入向量
System.out.println(victor.get(0.getValue());
//输出:7,即使我们更改了向量“object”的值
System.out.println(bar.getValue());