小编Jou*_*wee的帖子

泛型类和列表的奇怪编译错误

因此,当使用具有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)

java generics type-erasure

7
推荐指数
1
解决办法
127
查看次数

标签 统计

generics ×1

java ×1

type-erasure ×1