我有一个BiDiMap类。如何通过接受String
以及Object
类型的对象作为输入参数来保持所有原始功能的工作,如何使其成为通用的。例如,我希望能够使用函数put()
与Object
,Object
作为输入参数而不是String
,String
。我想更改所有输入参数并将String
类型的值返回到Object
类型。
package MyBiDiMap;
import java.util.HashMap;
import java.util.Map;
public class BiDiMap {
private Map<String, String> keyValue;
private Map<String, String> valueKey;
public BiDiMap() {
this.keyValue = new HashMap<>();
this.valueKey = new HashMap<>();
}
private BiDiMap(Map<String, String> keyValue,
Map<String, String> valueKey) {
this.keyValue = keyValue;
this.valueKey = valueKey;
}
public void put(String key, String value) {
if (this.keyValue.containsKey(key)
|| this.valueKey.containsKey(value)) {
this.remove(key);
this.removeInverse(value);
}
this.keyValue.put(key, value);
this.valueKey.put(value, key);
}
public String get(String key) {
return this.keyValue.get(key);
}
public String getInverse(String value) {
return this.valueKey.get(value);
}
public void remove(String key) {
String value = this.keyValue.remove(key);
this.valueKey.remove(value);
}
public void removeInverse(String value) {
String key = this.valueKey.remove(value);
this.keyValue.remove(key);
}
public int size() {
return this.keyValue.size();
}
public BiDiMap getInverse() {
return new BiDiMap(this.valueKey, this.keyValue);
}
}
答案非常简单:通过在类上引入两个名为K和V的泛型类型,然后用K(应该使用键类型)大力替换String的所有出现,并且类似于需要值的V。
换句话说:在声明两个映射时不要使用特定类型,但在所有地方,请使用您在类级别添加的新泛型类型。