David Torrey
David Torrey

Reputation: 1352

when would I use a shallow copy?

I understand what the difference between a shallow and deep copy are, but I really don't understand in what situations a shallow copy would be preferred.

If I'm not mistaken, shallow copy makes a new copy of the value types and simply copies the address of reference types so they are pointing to the same object, correct? Why would I ever want this effect?

Upvotes: 5

Views: 3706

Answers (2)

H Ketabi
H Ketabi

Reputation: 3154

I think one good example could help understanding the concept. Suppose you have a list of tuples. And you the list to a function to process something on. Creating some sub-lists from the original one could help in a function and this is not necessary to deep-copy all the tuples in the list. And you just need to copy those pointers (shallow-copy).

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109593

In fact a shallow copy is the way with least effort, doing less. It is especially suited for immutable objects, where sharing is optimal.

An immutable object does not have an internal state, cannot be changed, only variables can be set to another value.

In java String and BigDecimal are immutable.

Immutable objects allow making better use of threads too.

For mutable classes you might be interested in copy-on-write data structures, where sharing happens till one variable is written to.

Upvotes: 3

Related Questions