Joh*_*ohn 3 java overloading hashmap constructor-overloading
我有一个非常简单的问题但到目前为止找不到任何东西.
我正在尝试创建两个类构造函数.
第一个构造函数获取2个字符串和一个HashMap并初始化类变量.
public Foo(String a, String b, HashMap<String, String> c) {
this.a = a;
this.b = b;
this.c = c;
}
Run Code Online (Sandbox Code Playgroud)
第二个构造函数应该只获取2个字符串并创建一个"默认"-HashMap.
通常你只需要this()使用默认值调用,但我找不到用a做的方法HashMap.
public Foo(String a, String b) {
this(a, b, new HashMap<String, String>().put("x", "y").put("f","g"));
}
Run Code Online (Sandbox Code Playgroud)
Eclipse标记错误:
类型不匹配:无法转换
String为HashMap<String,String>
否则this()-call不能是函数中的第一个语句.
public Foo(String a, String b) {
HashMap<String, String> c = new HashMap<String, String>();
c.put("x", "y");
c.put("f", "g");
this(a, b, c);
}
Run Code Online (Sandbox Code Playgroud)
任何想法如何解决这个问题?
最糟糕的情况我不得不复制代码,但我想知道是否没有更好的方法.
如果此Map是常量,则可以将其存储为常量并重用它.这样可以避免每次Foo创建new时都重新创建Map,但之后会在所有Foos上共享.
public class Foo {
private static final Map<String, String> DEFAULT = new HashMap<>();
static {
DEFAULT.put("x", "y");
DEFAULT.put("f","g");
}
public Foo(String a, String b) {
this(a, b, DEFAULT);
}
public Foo(String a, String b, Map<String, String> c) {
this.a = a;
this.b = b;
this.c = c;
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以创建一个返回正确值的静态方法.请注意,该方法需要是静态的,因为您无法在其中调用实例方法this().
public class Foo {
public Foo(String a, String b) {
this(a, b, getDefaultMap());
}
public Foo(String a, String b, Map<String, String> c) {
this.a = a;
this.b = b;
this.c = c;
}
private static Map<String, String> getDefaultMap() {
Map<String, String> map = new HashMap<>();
map.put("x", "y");
map.put("f", "g");
return map;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1230 次 |
| 最近记录: |