如何定义 2 个具有 2 种不同类型的 HashMap 的构造函数?
2022-09-03 03:34:32
我有一个类,有2个HashMap字段,如下所示-
HashMap<String, Integer> map1;
HashMap<String, String> map2;
现在,我只想传递构造函数中的一个映射,即 map1 或 map2 的类型。但是,我无法使用不同类型的HashMaps定义2个不同的构造函数。这是解决此问题的方法吗?
我有一个类,有2个HashMap字段,如下所示-
HashMap<String, Integer> map1;
HashMap<String, String> map2;
现在,我只想传递构造函数中的一个映射,即 map1 或 map2 的类型。但是,我无法使用不同类型的HashMaps定义2个不同的构造函数。这是解决此问题的方法吗?
几个选项:
1) 一个构造函数,它同时接受两个映射,并且在传递 null 时是安全的。
public MyClass( Map<String, Integer> map1, Map<String, String> map2 ) {
if ( map1 != null ) { this.map1 = map1; }
if ( map2 != null ) { this.map2 = map2; }
}
2) 每张地图的二传手
public MyClass {
private Map<String, Integer> map1;
private Map<String, String> map2;
public void setMap1( Map<String, Integer> map1 ) {
this.map1 = map1;
}
public void setMap2( Map<String, String> map2 ) {
this.map2 = map2;
}
}
3)一个构建器,允许您区分映射并正确构造对象(调用设置者)
public MyClass {
private Map<String, Integer> map1;
private Map<String, String> map2;
// pretend you don't want people to be able to swap out the map after construction so you protect the setter here.
protected void setMap1( Map<String, Integer> map1 ) {
this.map1 = map1;
}
protected void setMap1( Map<String, String> map2 ) {
this.map2 = map2;
}
// getters for the maps and other properties
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Map<String, Integer> map1;
private Map<String, String> map2;
public Builder withMap1( Map<String, Integer> map ) {
map1 = map;
return this;
}
public Builder withMap2( Map<String, String> map ) {
map2 = map;
return this;
}
public MyClass build() {
MyClass c = new MyClass();
// possibly conditional code that inspects the maps for specific values or validity
c.setMap1( map1 );
c.setMap2( map2 );
// initialization of other fields
return c;
}
}
public static void main( String[] args ) {
// sample usage
MyClass instance1 = MyClass.builder().withMap1(myMap1).build();
MyClass instance2 = MyClass.builder().withMap2(myMap2).build();
MyClass instance3 = MyClass.builder().withMap1(myMap1).withMap2(myMap2).build();
}
}
4)静态工厂(正如叶甫根尼·多罗菲耶夫在下面指出的那样)
public MyClass {
private Map<String, Integer> map1;
private Map<String, String> map2;
// other properties
private MyClass() {}
public static MyClass withMap1(Map<String, Integer> map ) {
MyClass c = new MyClass();
c.map1 = map;
return c;
}
public static MyClass withMap2(Map<String, String> map ) {
MyClass c = new MyClass();
c.map2 = map;
return c;
}
// getters and setters
}
你不能:泛型在编译阶段被剥离:编译后的代码在这两种情况下都可以看到。HashMap<Object, Object>
此过程的技术名称是类型擦除。查看 http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
在许多方面,这使得Java泛型不如C++模板。