Pergunta

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! ♥

Foi útil?

Solução

In your context, what .slice() does is simply to make a copy of your vector, so that newArray refers to a different object from oldArray, except both seem like identical objects. Likewise goes for newVector and oldVector.

The second snippet:

Array newArray = oldArray;
Vector.<Foo> newVector = oldVector;

actually makes newArray a reference to oldArray. That means both variables refer to the same array. Same for newVector and oldVector — 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.

Also, what if the Vector's base type isn't Foo, but something simple and immutable like int?

It's the same, because your variables refer to the Vector objects and not their ints.

What is the result of the following?

Your output is correct:

something, something else, and another thing
something, something else, and the last thing

two = one.slice(), without any arguments, makes a new copy of one with all its current contents and assigns it to two. When you push each third item to one and two, you're appending to distinct Vector objects.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top