[英]Why cannot I create generic arraylist member of generic class?
I want to add methods to return the list or particular element and I want it to work with any generic class.我想添加方法来返回列表或特定元素,并且我希望它可以与任何通用 class 一起使用。 Why isnt Java allowing this?为什么 Java 不允许这样做?
class ArrayListBuilder<E>{
private ArrayList<E> a_list=new 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
.如您所见,实际上有两个错误,第一个意味着您需要导入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. TL;DR:您的问题的解决方案是阅读所有错误消息。 Not just the last one.不只是最后一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.