I suddenly thought of a question when I was coding a while ago. Usually our array is passed into the method as a parameter. What if we want to create an array in the method? When the type is clear, this is not difficult. What if the parameters we pass in are parameters of a generic type?
1 2 3 |
|
The above method of using T to create a new array directly is wrong, and an error will appear during compilation: Cannot create a generic array of T.. Java does not support directly creating arrays of unknown types.
Finally I got such a perfect solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
The code output is as follows:
1
2
3
4
5
6
7
8
9
10
11
ccc
//方法中输出的arr[1]
null
//以下5个是main中循环迭代出的数组值
ccc
null
null
null
Copy after loginCopy after login
The above method is completely feasible. We construct an array of a specifiable type by using the newInstance method of the Array class. It should also make sense to use reflection to do this job. Because the generic type T can only be determined at runtime, we must find a way to create a generic array at Java runtime. The only technology that works at Java runtime is reflection.
I also saw null, so I would like to sort out the values of different types of array initialization in Java:
Basic type (numeric type): 0
Basic type (boolean): false
Basic type (char type): (char) 0
Object type: null
I suddenly thought of a problem when I was coding a while ago. Usually our array is passed into the method as a parameter. What if we want to create an array in the method? When the type is clear, this is not difficult. What if the parameters we pass in are parameters of a generic type?
1 2 3 |
|
The above method of using T to directly create a new array is wrong, and an error will appear during compilation: Cannot create a generic array of T.. Java does not support directly creating arrays of unknown types.
Finally I got such a perfect solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
The code output is as follows:
1
2
3
4
5
6
7
8
9
10
11
ccc
//方法中输出的arr[1]
null
//以下5个是main中循环迭代出的数组值
ccc
null
null
null
Copy after loginCopy after login
The above method is completely feasible. We construct an array of a specifiable type by using the newInstance method of the Array class. It should also make sense to use reflection to do this job. Because the generic type T can only be determined at runtime, we must find a way to create a generic array at Java runtime. The only technology that can work at Java runtime is reflection.
I also saw null, so I would like to sort out the values of different types of array initialization in Java:
Basic type (numeric type): 0
Basic type (boolean): false
Basic type (char type): (char) 0
Object type: nul