英文:
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<E>{
private ArrayList<E> a_list=new ArrayList<>();
}
答案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<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
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论