public class TestOne { public void printMap() { Map map = new HashMap(); map.put("1", "1"); map.put("2", "2"); map.put("3", "3"); map.put("1", "4"); Iterator it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next(); System.out
.println("key = " + key + " ; value = " + map.get(key));
} } public static void main(String[] args) {
new TestOne().printMap();
} /**
* 问题: 如何不让不覆盖前一个的值
*
* 运行结果是:key = 3 ; value = 3
key = 2 ; value = 2
key = 1 ; value = 4
我需要的结果是:key = 3 ; value = 3
key = 2 ; value = 2
key = 1 ; value = 1
*/
while (it.hasNext()) {
Object key = it.next(); System.out
.println("key = " + key + " ; value = " + map.get(key));
} } public static void main(String[] args) {
new TestOne().printMap();
} /**
* 问题: 如何不让不覆盖前一个的值
*
* 运行结果是:key = 3 ; value = 3
key = 2 ; value = 2
key = 1 ; value = 4
我需要的结果是:key = 3 ; value = 3
key = 2 ; value = 2
key = 1 ; value = 1
*/
if (!map.containsKey(k))
map.put(k, v);
}
public static Object putNoOverrite(Map map, Object k, Object v) {
if (!map.containsKey(k))
return map.put(k, v);
return null;
}
这方法可行,你也可以写个类把Map的put方法重写下.