In general, arrays cannot be combined well with generics, and you cannot instantiate arrays with parameterized types. Erasing removes parameter type information, and arrays must know the exact type they hold. But we can parameterize the array itself.
1 Importjava.util.ArrayList;2 Importjava.util.Arrays;3 Importjava.util.LinkedList;4 Importjava.util.List;5 6 classClassparameter<t> {7 Publict[] F (t[] arg) {8 returnArg;9 }Ten } One A classMethodparameter { - Public Static<T>t[] F (t[] arg) { - returnArg; the } - } - - Public classParameterizedarraytype { + Public Static voidMain (string[] args) { - //list<string>[] ls = new list<string>[5];//Compile ERROR: Cannot instantiate an array with a parameterized type +list<string>[] ls =NewLIST[5];//this will ALs[0] =NewArraylist<>(); at //ls[1] = new arraylist<integer> ();//Compile ERROR: Type mismatch -LS[2] =NewLinkedlist<>(); - //but we can parameterize the array itself. -Integer[] INTs = {1, 2, 3, 4, 5}; -Double[] Doubles = {1.1, 2.2, 3.3, 4.4, 5.5}; -integer[] Ints2 =NewClassparameter<integer>(). f (ints); indouble[] Doubles2 =NewClassparameter<double>(). f (doubles); -System.out.println (arrays.tostring (ints2));//[1, 2, 3, 4, 5] toSystem.out.println (arrays.tostring (doubles2));//[1.1, 2.2, 3.3, 4.4, 5.5] +Ints2 =methodparameter.f (ints); -Doubles2 =METHODPARAMETER.F (doubles); theSystem.out.println (arrays.tostring (ints2));//[1, 2, 3, 4, 5] *System.out.println (arrays.tostring (doubles2));//[1.1, 2.2, 3.3, 4.4, 5.5] $ }Panax Notoginseng}
Java Array (2): Arrays and generics