hashmap和arraylist连接

时间:2015-01-18 16:01:40

标签: java arraylist hashmap

我的主要目的是让我的arraylist和hashmap始终连接。 在某种意义上连接意味着如果我在地图中添加任何东西,那么它应该在ArrayList中复制,反之亦然。 任何想法的人。

static Map<Integer,Employee> emp = new HashMap<Integer,Person>();
static ArrayList<Employee> ls = new ArrayList <Employee>(emp.values());

通过此代码添加HashMap中的任何内容都会被复制到列表中,但是当我从ArrayList中删除时,它不会反映在地图中。 请帮助。

2 个答案:

答案 0 :(得分:1)

只需使用emp.values()集合即可。它由地图和副verca支持。见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);

答案 1 :(得分:0)

你说:

  

连接在某种意义上意味着如果我在地图中添加任何东西,那么它应该被复制到ArrayList中,反之亦然。

但是让我们说你在数组列表中添加了一些内容,你希望密钥对于哈希映射是什么?

一旦你决定了每个用例的行为,我建议的解决方案就是编写你自己的添加和删除函数,它们总是在数组和哈希中添加/删除值。然后,您可以使用这些方法,这些方法包含Java提供的方法,而不是直接使用它们。