是否有可能從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中值的列表,因爲我想用自己的位置
- 訪問項目我想保留值的順序
- 如果我在提取的列表中修改任何內容,那麼它也應該反映在HashMap中
請不要告訴,如果任何第三方庫提供這樣的數據結構,或者這將是處理這種情況
'List list = new ArrayList <>(map.values());'你認爲這行代表什麼? –
Fildor
這是淺拷貝,你想要什麼? – Boola
劇透:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection) – Fildor