In Java, what is a shallow copy?
A shallow copy just copies the values of the references in the class. A deep copy copies the values. given:
class Foo {
private Bar myBar;
...
public Foo shallowCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar;
return newFoo;
}
public Foo deepCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar.clone(); //or new Bar(myBar) or myBar.deepCopy or ...
return newFoo;
}
}
Foo myFoo = new Foo();
Foo sFoo = myFoo.shallowCopy();
Foo dFoo = myFoo.deepCopy();
myFoo.myBar == sFoo.myBar => true
myFoo.myBar.equals(sFoo.myBar) => true
myFoo.myBar == dFoo.myBar => **false**
myFoo.myBar.equals(dFoo.myBar) => true
In this case the shallow copy has the same reference (==
) and the deep copy only has an equivalent reference (.equals()
).
If a change is made to the value of a shallowly copied reference, then the copy reflects that change because it shares the same reference. If a change is made to the value of a deeply copied reference, then the copy does not reflect that change because it does not share the same reference.
C-ism
int a = 10; //init
int& b = a; //shallow - copies REFERENCE
int c = a; //deep - copies VALUE
++a;
Result:
a is 11
*b is 11
c is 10
What is the difference between a deep copy and a shallow copy?
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
What is shallow copy?
Shallow copy is when you copy the references of objects in a data structure instead of copying the objects themselves and saving a copy of them (deep copy)
In this case I guess he is talking about the array of students. He probably wants you to save an array of a copy of each student (new student)
Is shallow copy really needed?
A container type like List<Point>
may in some cases be used to hold a bunch of X,Y coordinate pairs, but in other cases may be used to identify a bunch of movable points which are used by other code. The former case may be subdivided into subcases where the owner of the List<Point>
is also the exclusive owner of the Point
instances therein and may modify them at will, or where the owner will never modify those instances but may share references to them with code that promises not to modify them either.
If the List<Point>
is used to encapsulate (X,Y) coordinate pairs, but the the owner might modify the Point
objects held therein, then a proper clone of the List<Point>
must hold references to copies of the Point
objects in question. If it encapsulates coordinate pairs, but nobody will ever modify the objects therein (and recipients of a cloned list wouldn't expose references to the objects therein to any code that might modify them) then a proper clone of the List<Point>
could hold references to either the original Point
objects or copies thereof; the former would be faster, but the latter would still be semantically correct.
If the List<Point>
serves to identify Point
instances which may be modified by other code, and any such modification needs to be reflected in the List<Point>
itself, then a proper clone must hold references to the same Point
objects as the original list. If a clone were to instead hold copies of those Point
objects, then it would no longer hold the same semantic information as the original list.
If Java
had segregated collection types based upon whether they encapsulate value using exclusively owned mutable instances or shareable immutable instances, or whether they serve to identify the things therein, then it would be possible to have a single concept of "cloning", rather than requiring "deep" and "shallow" cloning. Without such a distinction between collection types, however, it's necessary to have cloning methods which can do whatever will be needed based upon the things in the collection.
Java: Why String is special in Deep Copy and Shallow copy?
You start with this situation:
Then you clone the User
object. You now have two User
objects; the variables user
and clone
refer to those two objects. Note that both their name
member variables refer to the same String
object, with the content "one"
.
Then you call setName("two")
on clone
, which will change the name
member variable of the second User
object to refer to a different String
object, with the content "two"
.
Note that the variable user
still refers to the User
object which has its name
member variable referring to "one"
, so when you System.out.println(user.getName());
the result is one
.
shallow copy - new instance Or assignment
While performing shallow copy is it necessary to "create a new
instance" ?
Yes, you must create an instance to create a copy (either shallow
or deep
) of your object. Just doing the assignment of reference just creates a copy of reference
which points to the same instance.
You have used a non-static method
that is creating a copy
. But generally I prefer two ways: -
Either use a copy-constructor
: -
public A(A obj) {
copy.aValue = obj.aValue;
}
And use it like: -
A first = new A();
A copy = new A(first);
Or, use a public static method
which takes an instance and returns a copy of that.
public static A createCopy(A obj) {
A copy = new A();
copy.aValue = obj.aValue;
return copy;
}
Related Topics
Given Final Block Not Properly Padded
Ray Casting with Different Height Size
Lombok Annotations Do Not Compile Under Intellij Idea
Spring Security Configuration - Httpsecurity VS Websecurity
Maven - Always Download Sources and Javadocs
Green Threads VS Non Green Threads
How to Handle Pop-Up in Selenium Webdriver Using Java
How Does Java "Week Year" Really Work
How to Handle Very Large Numbers in Java Without Using Java.Math.Biginteger
How to Create Table Using Ascii in a Console
When to Use Wrapper Class and Primitive Type
How to Split a Java String at Backslash
How to Create Custom Methods for Use in Spring Security Expression Language Annotations
How to Make My Arraylist Thread-Safe? Another Approach to Problem in Java
Why Start an Arraylist with an Initial Capacity
How to Open the Command Prompt and Insert Commands Using Java