那天无意间看到一个博客,写到关于Map 元素覆盖的问题,特意做了一个例子验证了一下:
package com.javaeye.demo;
public class Apple {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Apple other = (Apple) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
定义了一个Apple类,重写了hashCode 和 equals 方法,name相同的话2个对象就相等。
接下来是测试类:
package com.javaeye.demo;
import java.util.HashMap;
import java.util.Map;
public class AppleMain {
public static void main(String[] args) {
Apple apple1 = new Apple();
apple1.setName("APPLE");
apple1.setAddress("Beijing");
Apple apple2 = new Apple();
apple2.setName("APPLE");
apple2.setAddress("Shanghai");
Map<Apple, String> map = new HashMap<Apple, String>();
map.put(apple1, "A");
map.put(apple2, "B");
for(Map.Entry<Apple, String> entry:map.entrySet()) {
System.out.println(entry.getKey().getAddress() + "-" + entry.getValue());
}
}
}
猜猜答案:
1) Beijing-A
2) Beijing-B
3) Shanghai-A
4) Shanghai-B
我相信大部分的人会选择4)把,其实正确答案是2)。 Map 覆盖的时候KEY是不会被覆盖的,只会覆盖VALUE的值。
值得注意。