سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top