我的主要目的是让我的arraylist和hashmap始终连接。 从某种意义上说,连接意味着如果我在 map 中添加任何内容,那么它应该被复制到 ArrayList 中,反之亦然。 大家有什么想法吗?
static Map<Integer,Employee> emp = new HashMap<Integer,Person>();
static ArrayList<Employee> ls = new ArrayList <Employee>(emp.values());
通过这段代码,我在 HashMap
中添加的任何内容都会被复制到列表中,但是当我从 ArrayList
中删除时,它不会反射(reflect)在 map 中。
请帮忙。
最佳答案
只需使用 emp.values()
Collection 。它有 map 和反之亦然的支持。请参阅http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#values()
Collection<Employee> ls = emp.values();
如果您从此 Collection
中删除某些内容,它将从 HashMap
中删除以及。
在您的示例中,您正在创建一个新的 ArrayList
并将所有元素的引用复制到其中。当然是这个新的ArrayList
不认识你 HashMap
.
一个简短的例子:
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
// Output is "{1=One, 2=Two, 3=Three}"
System.out.println(map);
Collection<String> backedUpCollection = map.values();
// Remove something from collection and check the maps content
backedUpCollection.remove("Two");
// Output is "{1=One, 3=Three}"; "Two" was removed
System.out.println(map);
// Add an entry to the map and check the content of collection
map.put(4, "Four");
// Output is "[One, Three, Four]"; "Four" was added
System.out.println(backedUpCollection);
关于java - hashmap 和 arraylist 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28011755/