首页 新闻 会员 周边 捐助

java并发实战 对象组合问题

0
悬赏园豆:5 [已关闭问题] 关闭于 2017-06-08 17:21
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class DelegatingVehicleTracker {
    private final ConcurrentMap<String, Point> locations;
    private final Map<String,Point> unmodifiableMap;
    
    public DelegatingVehicleTracker(Map<String,Point> map){
        locations = new  ConcurrentHashMap<String,Point>(map);
        unmodifiableMap = Collections.unmodifiableMap(map);
    }
    
//A:
    public Map<String,Point> getLocations(){ 
        return unmodifiableMap;
    }
//B:
    //返回locations的静态拷贝而非实时拷贝
    /*public Map<String,Point> getLocations(){
        return Collections.unmodifiableMap(new HashMap<>(locations));
    }*/
    
    public Point getLocation(String id){
        return locations.get(id);
    }
    public void setLocation(String id, int x, int y){
        this.locations.replace(id, new Point(x, y));
    }
    
    public static void main(String[] args) {
        DelegatingVehicleTracker tracker = new DelegatingVehicleTracker(new HashMap<String,Point>(){{
            put("a",new Point(11, 2));
            put("b",new Point(1, 3));
        }});
        System.out.println(tracker.getLocation("a"));
        tracker.setLocation("a",3,5);//修改数据
        System.out.println(tracker.getLocation("a"));
    //如果调用A方法,返回的将是{a:Point(11, 2),b:Point(1,3)},  
    //如果调用B方法,返回是{a:Point(3, 5),b:Point(1,3)}
        Map<String, Point> locations2 = tracker.getLocations();
        System.out.println(locations2);
    }
}

class Point{
    public final int x,y;
    
    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point [x=" + x + ", y=" + y + "]";
    }
    
}

并发实战第四章对象组合中,基于委托的车辆追踪器

书中说A方法返回的是实时的数据,B方法返回的是不变化的数据,我怎么感觉是说反了?A方法返回的是unmodifiableMap,代码中并没有修改这个对象的地方,而B返回的是locations的一个潜拷贝,这个locations不是可以在setLocation中修改吗,那B方法返回的才应该是实时数据才对,是我哪里理解错了吗

until-u的主页 until-u | 菜鸟二级 | 园豆:225
提问于:2017-06-05 12:07
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册