java中参数化ArrayList的通用数组?
我是 Java 新手,所以我不知道具体细节。
为什么我无法创建参数化 ArrayList 的通用数组?
相反,我必须编写,
ArrayList<String>[] alist = new ArrayList[10];
或者我必须创建 ArrayList 列表。
数组不是应该比 ArrayList 更高效吗?那为什么Java不允许呢?
另外,以下两行有什么区别。
ArrayList<String>[] alist = new ArrayList[10];
ArrayList<String>[] alist = new ArrayList<?>[10];
I am new to Java, so I am not aware of the nitty gritties.
Why can't I create generic array of parametrized ArrayList?
Instead I have to write,
ArrayList<String>[] alist = new ArrayList[10];
or I have to create List of ArrayLists.
Aren't arrays supposed to be more efficient than ArrayLists? Then why doesn't Java allow it?
Also, what is the difference between following two lines.
ArrayList<String>[] alist = new ArrayList[10];
ArrayList<String>[] alist = new ArrayList<?>[10];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须这样做的原因是因为 Java 中真正不存在泛型。它实际上是一个编译器黑客。
至于您发布的两行,产生的字节码不应该有任何差异。但是,在第一种情况下,您可能会收到警告,因为编译器认为您忘记了 java.util.ArrayList 需要类型参数,而后者不会编译,因为您正在尝试实例化一个通用数组。双输的情况:(
The reason you have to do that is because generics don't really exist in Java. It's actually a compiler hack.
As for the two lines you posted, there shouldn't be any difference in terms of the bytecode produced. However, in the first case you'll probably get a warning because your compiler thinks you forgot
java.util.ArrayList
wants a type parameter, whereas the latter won't compile because you're trying to instantiate a generic array. Lose-lose situation :(实际上,ArrayList 的实现对于不改变列表大小的读写操作非常有效。在许多情况下(至少从 java 1.6 开始),编译器将完全消除方法调用开销(例如 get())。
此外,没有多少程序需要数组提供的性能,因此不必担心使用数组,直到您的代码太慢(即使这样,您可能也不需要数组)
Actually the implementation of ArrayList is very efficient for read and write actions that don't change the size of the list. In many cases (at least since java 1.6) the compiler will totally remove the method call overhead (for instance for get()).
Also not many programs require the performance that an array offers, so don't worry about using arrays until your code is too slow (and even then you probably don't need the arrays)
如果你能做到这一点,就会发生这样的情况:
If you could do that, this will happen :
我还建议创建一个数组列表的数组列表。
,其中 Type 是您想要列表的任何类型。您现在拥有一个保存数组列表的数组列表。如果你想添加一个数组列表,你可以这样做:
I would also recommend creating an arraylist of arraylists.
, where Type is whatever type you wanted the list to be. You now have an arraylist that holds array lists. If you want to add an arraylist, you can do: