因此,当使用具有List(或Map或Set等)作为属性的泛型类时,我遇到了一个奇怪的编译错误.
尝试迭代(使用foreach)List时发生编译错误:
Sample.java:11: error: incompatible types
for (String string : s.getStringList()) {
required: String
found: Object
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,我知道这个问题有一个简单的解决方法,但我想了解代码有什么问题
以下是我创建的示例:
import java.util.List;
public class Sample<T> {
public List<String> stringList;
public static void main(String[] args) {
Sample s = new Sample();
// Why this doesn't work?
for (String string : s.getStringList()) {
}
// Why does both of the following work?
List<String> newList = s.getStringList();
Sample<Object> s2 = new Sample<>();
for (String string : s2.getStringList()) {
}
}
public List<String> getStringList() { …Run Code Online (Sandbox Code Playgroud)