Does shallow copy work as deep copy in case of immutable objects in java?

madcolonel10 :

I am reading java concurrency in practice. I came across this snippet which is causing me some confusion. If an unchanging view of the fleet is required, getLocations could instead return a shallow copy of the locations map. Since the contents of the Map are immutable, only the structure of the Map, and not the contents must be copied.

public Map<String,Point> getLocations(){
 return Collections.unmodifiableMap(new HashMap<String,Point>(locations));
}

To return an unmodifiable but live view of the vehicle locations.

public Map<String,Point> getLocations(){
return unmodifiableMap; //unmodifiableMap = Collections.unmodifiableMap(locations);
}
public class Point{
 public final int x,y;
 public Point(int x, int y){
  this.x = x;
  this.y=y;
 }
}
public void setLocation(String id,int x,int y){
 if(locations.replace(id,new Point(x,y==null)
   //throw exception for invalid vehicle
}

Does this imply that new HashMap<String,Point>(locations) is doing a deep copy of the locations map and assigning a new reference by creating a new object for Point when the copy is happening. Shouldn't shallow copy new HashMap<String,Point>(locations) retain the original reference to Point objects, and the change be visible in all threads.

Joni :

There is no need for a deep copy because the Point objects are immutable and cannot change. This is asserted in:

Since the contents of the Map are immutable

If the Point objects were mutable you would in deed have to make a deep copy.

The difference between the two implementations if getLocations refers to visibility to changes in the "structure" of the map. The first implementation returns an unmodifiable view of a copy of the map. If locations are added or removed after the method returns, it will not be visible in the map returned by this method. The second returns an unmodifiable view of the map itself. Any changes made after the method returns will be visible to the caller.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=355483&siteId=1