简体   繁体   English

在java中的不可变对象的情况下,浅拷贝是否可以作为深拷贝工作?

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

I am reading java concurrency in practice.我正在实践中阅读 java 并发。 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.如果需要车队的不变视图,getLocations 可以改为返回位置地图的浅表副本。 Since the contents of the Map are immutable, only the structure of the Map, and not the contents must be copied.由于 Map 的内容是不可变的,因此只需要复制 Map 的结构,而不需要复制内容。

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.这是否意味着new HashMap<String,Point>(locations)正在执行位置映射的深层复制,并在复制发生时通过为 Point 创建新对象来分配新引用。 Shouldn't shallow copy new HashMap<String,Point>(locations) retain the original reference to Point objects, and the change be visible in all threads.不应该浅拷贝new HashMap<String,Point>(locations)保留对 Point 对象的原始引用,并且更改在所有线程中都是可见的。

There is no need for a deep copy because the Point objects are immutable and cannot change.不需要深拷贝,因为 Point 对象是不可变的,不能改变。 This is asserted in:这是断言:

Since the contents of the Map are immutable由于 Map 的内容是不可变的

If the Point objects were mutable you would in deed have to make a deep copy.如果 Point 对象是可变的,您确实必须进行深度复制。

The difference between the two implementations if getLocations refers to visibility to changes in the "structure" of the map.如果 getLocations 是指对地图“结构”变化的可见性,则两种实现之间的区别。 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.方法返回后所做的任何更改对调用者都是可见的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM