我在使用Java的泛型类型参数推断方面遇到了一些困难。考虑下面这个类,它有一个可选的列表参数:
import java.util.Collections;
import java.util.List;
public class Person {
private String name;
private List<String> nicknames;
public Person(String name) {
this(name, Collections.emptyList());
}
public Person(String name, List<String> nicknames) {
this.name = name;
this.nicknames = nicknames;
}
}
我的Java编译器报错如下:
Person.java:9: The constructor Person(String, List<Object>) is undefined
但是 Collections.emptyList()
返回的类型为 <T> List<T>
,而不是 List<Object>
。强制类型转换并不能解决问题。
public Person(String name) {
this(name,(List<String>)Collections.emptyList());
}
产生的结果Person.java:9: inconvertible types
使用EMPTY_LIST
代替emptyList()
public Person(String name) {
this(name, Collections.EMPTY_LIST);
}
产出。Person.java:9: warning: [unchecked] unchecked conversion
而以下更改使错误消失:
public Person(String name) {
this.name = name;
this.nicknames = Collections.emptyList();
}
有人能够解释我这里遇到的类型检查规则是什么,以及最好的解决方法是什么吗?在这个例子中,最后的代码示例是令人满意的,但对于更大的类,我想能够编写遵循这种“可选参数”模式的方法,而不需要重复代码。
额外加分:何时适合使用EMPTY_LIST
而不是emptyList()
?