java中创建一个项目没有map,Java:如何在一个类中创建私有字段Map不可变?

public class Hi {

private final Map map;

public Map getMap() {

return map;

}

}

I have this Hi class, and I want map to be immutable. I also need a getter. Currently, another class can modify the map from the getter. I would like to return a copy of the map to solve this problem, but Map is an interface, so does that mean I have to make the getter call:

return new HashMap(map);

Is there another way to do it without forcing the map to be a hashmap? I would like for it to remain the same class as before.

解决方案

Return Collections.unmodifiableMap(map), which provides an unmodifiable view of the Map it wraps. Quoting from the Javadocs for that method:

Returns an unmodifiable view of the specified map. This method allows

modules to provide users with "read-only" access to internal maps.

Query operations on the returned map "read through" to the specified

map, and attempts to modify the returned map, whether direct or via

its collection views, result in an UnsupportedOperationException.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值