通用双向映射
Generic BiDiMap
我有一个 BiDiMap class。我怎样才能使它通用,不仅接受 String
而且 Object
类型的对象作为输入参数,同时保持所有原始函数的工作。例如,我希望能够使用带有 Object
、Object
作为输入参数的函数 put()
,而不是 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);
}
}
答案非常简单:通过在 class 上引入两个泛型类型,分别命名为 K 和 V,然后用 K(应该使用您的键类型的地方)大力替换所有出现的字符串,以及与需要值的 V 类似。
换句话说:在声明两个映射时不要使用特定类型,而是在所有地方使用您在 class 级别添加的新通用类型。
我有一个 BiDiMap class。我怎样才能使它通用,不仅接受 String
而且 Object
类型的对象作为输入参数,同时保持所有原始函数的工作。例如,我希望能够使用带有 Object
、Object
作为输入参数的函数 put()
,而不是 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);
}
}
答案非常简单:通过在 class 上引入两个泛型类型,分别命名为 K 和 V,然后用 K(应该使用您的键类型的地方)大力替换所有出现的字符串,以及与需要值的 V 类似。
换句话说:在声明两个映射时不要使用特定类型,而是在所有地方使用您在 class 级别添加的新通用类型。