是否可以从 HashMap
中获取值列表作为引用
class MyCustomObject {
String name;
Integer id;
MyCustomObject(String name, Integer id){
this.name = name;
this.id = id;
}
}
HashMap<Integer, MyCustomObject> map = new LinkedHashMap<>();
map.put (1, new MyCustomObject("abc",1));
map.put (2, new MyCustomObject("xyz",2));
List<MyCustomObject> list = new ArrayList<>(map.values());
Log.i(TAG,"************ List from HashMap ************");
for (MyCustomObject s : list) {
Log.i(TAG,"name = "+s.name);
}
list.set(0,new MyCustomObject("temp",3));
Log.i(TAG,"************ List from HashMap after update ************");
for (MyCustomObject s : list) {
Log.i(TAG,"name = "+s.name);
}
Log.i(TAG,"************ List from HashMap ************");
List<MyCustomObject> list2 = new ArrayList<>(map.values());
for (MyCustomObject s : list2) {
Log.i(TAG,"name = "+s.name);
}
输出
**************** List from HashMap ***************
name = abc
name = xyz
**************** List from HashMap after update ***************
name = temp
name = xyz
**************** List from HashMap ***************
name = abc
name = xyz
如果从 HashMap
中获取值列表,它会返回深度复制。
更新
我的需求
- 我想要来自 HashMap 的值列表,因为我想使用它们的位置访问项目
- 我想保留值的顺序
- 如果我修改提取列表中的任何内容,那么它也应该反射(reflect)在 HashMap 中
请告诉,如果任何第三方库提供这种数据结构,或者处理这种情况的最佳方法是什么
最佳答案
您正在根据 Map
的值创建一个新的 List
:
List<MyCustomObject> list = new ArrayList<>(map.values());
这就是创建值 Collection
副本的原因,List
中的更改无法反射(reflect)在原始 Map
中。
如果直接修改map.values()
返回的Collection(例如,map.values().remove(new MyCustomObject("abc",1))
),它会反射(reflect)在原始Map
的内容中。但是,您将无法在 Collection
上调用 set
,因为 Collection
没有该方法。
关于java - 从 HashMap 获取值作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942765/