为什么不能创建泛型类的泛型数组列表成员?

huangapple go评论80阅读模式
英文:

Why cannot I create generic arraylist member of generic class?

问题

我想要添加用于返回列表或特定元素的方法,并且我希望它适用于任何通用类。为什么Java不允许这样做?

class ArrayListBuilder<E> {
    private ArrayList<E> a_list = new ArrayList<>();
}
英文:

I want to add methods to return the list or particular element and I want it to work with any generic class. Why isnt Java allowing this?

class ArrayListBuilder&lt;E&gt;{
	private ArrayList&lt;E&gt; a_list=new ArrayList&lt;&gt;();
}

答案1

得分: 2

我尝试编译您的代码并得到了以下错误:

ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list = new ArrayList<>();
            ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list = new ArrayList<>();
                                    ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
2 errors

正如您所见,实际上有两个错误,第一个错误意味着您需要导入 java.util.ArrayList。一旦您这样做,您的代码就可以正常编译。所以请在您的代码第一行添加:

import java.util.ArrayList;

简而言之:解决您的问题的方法是阅读所有错误消息,而不仅仅是最后一个。

英文:

I tried to compile your code and got these errors

ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList&lt;E&gt; a_list=new ArrayList&lt;&gt;();
            ^
  symbol:   class ArrayList
  location: class ArrayListBuilder&lt;E&gt;
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList&lt;E&gt; a_list=new ArrayList&lt;&gt;();
                                    ^
  symbol:   class ArrayList
  location: class ArrayListBuilder&lt;E&gt;
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
2 errors

As you can see there actually are two errors, the first one meaning that you need to import java.util.ArrayList. Once you do that, your code compiles fine. So put in the first line of your code

import java.util.ArrayList;

TL;DR: the solution to your problem is reading all of the error messages. Not just the last one.

huangapple
  • 本文由 发表于 2020年5月30日 16:14:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/62099649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定