I am copying a vector to another vector of same type.And modifying the copy vector but the original vector is also getting update I don't understand why?
Vector<allocated>finished_copy=new Vector<allocated>();
finished_copy=finished;
I am printing the value of original vector after and before modification
for(int k=0;k<finished.size();k++) {
System.out.print(finished.elementAt(k).output);
System.out.print(finished.elementAt(k).step);
System.out.println();
}//some modification on finished_copy
And printing the original but both are different
Please help me in this
You're not doing any copy. All you're doing is assigning the same Vector to another variable:
Before:
finished ------> [a, b, c, d]
After:
finished ------> [a, b, c, d]
^
|
finished_copy ---/
Here's how you would copy all the elements of a Vector into another one:
Vector<Allocated> finishedCopy = new Vector<>(finished);
or
Vector<Allocated> finishedCopy = new Vector<>();
finishedCopy.addAll(finished);
This, however, will create two different vectors containing references to the same Allocated instances. If what you want is a copy of those objects, then you need to create explicit copies. Without doing a copy, changing the state of an object in the first list will also change its state in the second one, since both lists contain references to the same ojects.
Note that:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments