不知道你的“重复key”是指什么?是两个对象equals()还是它们的hashCode()相同?
hashCode()相同肯定是允许的,
而两个对象equals()时,一般它们的hashCode也是相同的,所以很少看到所谓的重复key,但你完全可以打破这的约定
import java.util.*;public class MyKey {
public MyKey() {
} public int hashCode() {
int hash = 0;
if (Math.random() < 0.5) {
hash = 1;
}
return hash;
} public boolean equals(Object o) {
if (this == o)
return false; return false;
} public static void main(String[] args) {
MyKey key = new MyKey();
HashMap map = new HashMap();
for (int i = 0; i < 100; i++) {
map.put(key, new Integer(i));
} for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getValue());
}
}
}
hashCode()相同肯定是允许的,
而两个对象equals()时,一般它们的hashCode也是相同的,所以很少看到所谓的重复key,但你完全可以打破这的约定
import java.util.*;public class MyKey {
public MyKey() {
} public int hashCode() {
int hash = 0;
if (Math.random() < 0.5) {
hash = 1;
}
return hash;
} public boolean equals(Object o) {
if (this == o)
return false; return false;
} public static void main(String[] args) {
MyKey key = new MyKey();
HashMap map = new HashMap();
for (int i = 0; i < 100; i++) {
map.put(key, new Integer(i));
} for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getValue());
}
}
}
import java.util.*;public class MyKey {
public MyKey() {
} public int hashCode() {
int hash = 0;
if (Math.random() < 0.5) {
hash = 1;
}
return hash;
} public boolean equals(Object o) {
if (this == o)
return true; return false;
} public static void main(String[] args) {
MyKey key = new MyKey();
HashMap map = new HashMap();
for (int i = 0; i < 100; i++) {
map.put(key, new Integer(i));
} for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getValue());
}
}
}