ActionScript's Array and Vector classes both have a slice() method. If you don't pass any parameters, the new Array or Vector is a duplicate (shallow clone) of the original Vector.
What does it mean to be a "shallow clone"? Specifically, what is the difference between
Array newArray = oldArray.slice();
Vector.<Foo> newVector = oldVector.slice();
and
Array newArray = oldArray;
Vector.<Foo> newVector = oldVector;
? Also, what if the Vector's base type isn't Foo, but something simple and immutable like int?
Update:
What is the result of the following?
var one:Vector.<String> = new Vector.<String>()
one.push("something");
one.push("something else");
var two:Vector.<String> = one.slice();
one.push("and another thing");
two.push("and the last thing");
trace(one); // something, something else, and another thing
trace(two); // something, something else, and the last thing
Thanks! ♥
In your context, what
.slice()does is simply to make a copy of your vector, so thatnewArrayrefers to a different object fromoldArray, except both seem like identical objects. Likewise goes fornewVectorandoldVector.The second snippet:
actually makes
newArraya reference tooldArray. That means both variables refer to the same array. Same fornewVectorandoldVector— both end up referring to the same vector. Think of it as using a rubber stamp to stamp the same seal twice on different pieces of paper: it's the same seal, just represented on two pieces of paper.On a side note, the term shallow copy differs from deep copy in that shallow is a copy of only the object while deep is a copy of the object and all its properties.
It's the same, because your variables refer to the
Vectorobjects and not theirints.Your output is correct:
two = one.slice(), without any arguments, makes a new copy ofonewith all its current contents and assigns it totwo. When you push each third item tooneandtwo, you're appending to distinctVectorobjects.