所以我试图创建一个名为 UniqueHashMap 的 HashMap 类的扩展,它具有 HashMap 类的所有属性,但是不能重复键,不能重复值。如果重复值,则替换键,例如:
Apple
->Green
我试着put("Pear", "Green")
我们不会有:Pear
->Green
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class UniqueHashMap extends HashMap {
public UniqueHashMap() {
}
public UniqueHashMap(int arg0) {
super(arg0);
}
public UniqueHashMap(Map arg0) {
super(arg0);
}
public UniqueHashMap(int arg0, float arg1) {
super(arg0, arg1);
}
public V put(K k, V v){
Set entrySet = (Set) hash.entrySet(); //Store entry of HashMap in a set
Iterator entryIterator = entrySet.iterator(); //Create iterator for the set
if(hash.containsValue(v))
{
while(entryIterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry) entryIterator.next();
String key = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
System.out.println("Key is = " + key + " and Value is = " + value);
System.out.println();
if (value.equals(v))
{
hash.remove(key);
hash.put(v, value);
break;
}
}
System.out.println(hash);
}
}
如您所见,我拥有超类的所有构造函数,但是它不会解析它应该从HashMap
类中继承的值(K、V、Hash、Map)
我做错扩展了吗?还是我错过了一些进口?