Java does not support generic arrays. Other words
[Java]View Plaincopy
- list<string>[] ls = new arraylist<string>[10];
is not supported, and
[Java]View Plaincopy
- list<string>[] ls = new arraylist[]
But you can.
Yes, I'm not sure. Why can't I declare an array of generics, specifying a type so that you don't have type-safe hints when compiling.
It was not until today that I saw a document from Sun that it was clear that a situation was mentioned:
[Java]View Plaincopy
- list<string>[] LSA = new list<string>[10]; //Not really allowed.
- Object o = LSA;
- Object[] OA = (object[]) o;
- list<integer> li = new arraylist<integer> ();
- Li.add (new Integer (3));
- oa[1] = Li; //unsound, but passes run time store check
- String s = lsa[1].get (0); //Run-time error:classcastexception.
In this case, because of the JVM generic erasure mechanism, the JVM is not aware of the generic information at runtime, so it is possible to assign a arraylist<integer> to oa[1] without appearing arraystoreexception, However, when the data is taken to do a type conversion, so there will be classcastexception, if you can make a generic array of declarations, the above-mentioned situation in the compilation period will not have any warnings and errors, only when the runtime error. Instead of restricting the declaration of a generic array, it is much better to have a type-safety problem with the code at compile time than to have no hint.
For the above reasons, Java does not support declaring generic arrays, more precisely: the type of an array cannot be a type variable, unless it is in the form of a wildcard , see the following example:
[Java]View Plaincopy
- list<?>[] LSA = new list<?>[10]; //OK, array of unbounded wildcard type.
- Object o = LSA;
- Object[] OA = (object[]) o;
- list<integer> li = new arraylist<integer> ();
- Li.add (new Integer (3));
- oa[1] = Li; //Correct.
- string s = (string) lsa[1].get (0); //Run time error, but cast is explicit.
Because of the way the wildcard is done, the final fetch of the data is to do an explicit type conversion, so there is no problem with the previous example.
Java Generic Array