创建一个数组来存储Java中的泛型类型 [英] Creating an array to store generic types in Java
问题描述
下面的代码将执行此操作:
ArrayList< Integer> [] pl2 = new ArrayList [10];
问题1:
在我看来,更合适的代码是
ArrayList< Integer> [] pl2 = new ArrayList< Integer> [10];
为什么这不起作用?
问题2:
以下两种编译
-
ArrayList< Integer> [] pl2 = new ArrayList [10];
-
ArrayList [] pl3 = new ArrayList [10];
参考声明的区别是什么? c $ c> pl2 和 pl3
是否值得关注?
问题1:
基本上,这是Java语言禁止的。这包括在泛型的Java语言规范中。
当您使用
ArrayList< Integer> [] pl2 = new ArrayList [10]; //警告
你会得到编译器警告,因为下面的例子会编译(为每行产生警告):
$ $ $ $ $ $ $ $ $ $ $ ArrayList wrongRawArrayList = new ArrayList(); //警告
wrongRawArrayList.add(string1); //警告
wrongRawArrayList.add(string2); //警告
pl2 [0] = wrongRawArrayList; //警告
但现在你的数组,应该包含 问题2: , 稍微修改过的例子: 现在,由于您使用的是泛型,因此无法编译。 您将获得与第一个示例中相同的结果。 Suppose I have to create an array which stores ArrayList's of Integers and the array size is 10. The below code will do it: Question 1: In my opinion the more appropriate code would be Why does this not work? Question 2: Both of the below compile What is the difference as far as the reference declaration of Question 1: Basically, this is forbidden by Java language. This is covered in Java Language Specification for generics. When you use you get the compiler warning, because the following example will compile (generating warning for every line of code): but now you array, that supposed to contain Question 2: As it was already answered, declaration of Slightly modified previous example: Now, since you are using generics, this won't compile.
But if you use you will get the same result as in the first example. 这篇关于创建一个数组来存储Java中的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ArrayList
整数
,包含完全错误
的ArrayList
字符串$ c
p12
声明为您提供编译时检查,并在从 ArrayList
中获取项目时使用cast来释放。
ArrayList< Integer> [] pl2 = new ArrayList [10]; //警告
ArrayList< String> wrongArrayList = new ArrayList< String>(); // 好!
wrongArrayList.add(string1); // 好!
wrongArrayList.add(string2); // 好!
pl2 [0] = wrongArrayList; //错误
但是如果你使用
$ pre $ Array $ [] pl2 = new ArrayList [10];
ArrayList<Integer>[] pl2 = new ArrayList[10];
ArrayList<Integer>[] pl2 = new ArrayList<Integer>[10];
ArrayList<Integer>[] pl2 = new ArrayList[10];
ArrayList[] pl3 = new ArrayList[10];
pl2
and pl3
is concerned?ArrayList<Integer>[] pl2 = new ArrayList[10]; // warning
ArrayList wrongRawArrayList = new ArrayList(); // warning
wrongRawArrayList.add("string1"); // warning
wrongRawArrayList.add("string2"); // warning
pl2[0] = wrongRawArrayList; // warning
ArrayList
of Integer
, contains totally wrong ArrayList
of String
objects.p12
provides you with compile time checking and frees you from using casting when getting items from your ArrayList
.ArrayList<Integer>[] pl2 = new ArrayList[10]; // warning
ArrayList<String> wrongArrayList = new ArrayList<String>(); // OK!
wrongArrayList.add("string1"); // OK!
wrongArrayList.add("string2"); // OK!
pl2[0] = wrongArrayList; // ERROR
ArrayList[] pl2 = new ArrayList[10];