我对以下代码有两个问题:
1)在这种情况下我有什么办法implement Map
,而不是只扩展接口的一个直接实现?我不想写一个完整的 Map 实现。但是很高兴看到我的实现并不关心正在使用的底层 Map 实现。2)有什么不好的做法吗?
ExtremesMap.java
package ocr.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author student
*/
public class ExtremesMap extends HashMap<String, Integer> {
private Set<String> smallest;
private int smallestValue;
private Set<String> biggest;
private int biggestValue;
public ExtremesMap() {
super();
smallest = new HashSet<>();
smallestValue = Integer.MAX_VALUE;
biggest = new HashSet<>();
biggestValue = Integer.MIN_VALUE;
}
@Override
public void put(String key, Integer value) {
if (value == null) {
throw new IllegalArgumentException("ocr.util.ExtremesMap.put: value == null");
}
//TODO for real performance application implement own type of Map directly
Integer retrieveValue = super.get(key);
if (retrieveValue != null) {
throw new IllegalStateException("ocr.util.ExtremesMap.put: Not allowed to modify existing value: key = " + key);
}
else if (retrieveValue == value) {
return;
}
super.put(key, value);
if (value < smallestValue) {
smallest = new HashSet<>();
smallestValue = value;
}
else if (value == smallestValue) {
smallest.add(key);
}
if (value > biggestValue) {
biggest = new HashSet<>();
biggestValue = value;
}
else if (value == biggestValue) {
biggest.add(key);
}
}
public String getSmallestString() {
if (smallest.size() != 1) {
throw new IllegalStateException("ocr.util.ExtremesMap.getSmallest: smallest.size() != 1: smallest.size() = " + smallest.size());
}
return smallest.iterator().next();
}
public Set<String> getSmallestSet() {
return smallest;
}
public List<String> getSmallestList() {
return Arrays.asList(getSmallestArray());
}
public String[] getSmallestArray() {
return smallest.toArray(new String[smallest.size()]);
}
public String getBiggestString() {
if (biggest.size() != 1) {
throw new IllegalStateException("ocr.util.ExtremesMap.getBiggest: biggest.size() != 1: biggest.size() = " + biggest.size());
}
return biggest.iterator().next();
}
public Set<String> getBiggestSet() {
return biggest;
}
public List<String> getBiggestList() {
return Arrays.asList(getBiggestArray());
}
public String[] getBiggestArray() {
return biggest.toArray(new String[biggest.size()]);
}
}
还有一个我无法解决的错误put()
:
方法不会覆盖或实现超类型中的方法
put(String,Integer) in ExtremesMap cannot implement put(K,V) in Map
return type void is not compatible with Integer
where K,V are type-variables:
K extends Object declared in interface Map
V extends Object declared in interface Map
这里到底出了什么问题?
问候。