Problems with Using Generics in java-13.15 from the beginning (1)-basic types cannot be used for generics
In this section, we will discuss the problems that occur when using generics.
The first problem we introduced today is that basic types cannot be used for generics.
1. Example
package com.ray.ch13;import java.util.ArrayList;public class Test {public static void main(String[] args) {// ArrayList
list;//errorArrayList
list = new ArrayList
();}}
Observe the code above and you can see that the generic type can only use Integer, but cannot use int.
However, the automatic packaging mechanism in java provides the possibility of implementation.
Modify the code above:
package com.ray.ch13;import java.util.ArrayList;public class Test {public static void main(String[] args) {// ArrayList
list;//errorArrayList
list = new ArrayList
();for (int i = 0; i < 10; i++) {list.add(i);}}}
In fact, I is of the int type, but it is directly converted to the Integer type through the automatic packaging mechanism.
However, as the number increases, the above Code will undoubtedly have very high performance problems, which is a hidden risk.
2. The automatic packaging mechanism is not omnipotent.
Example:
We will use a generator to create and load objects.
package com.ray.ch13;public class Test {public static void main(String[] args) {// FillArray.fill(new int[5], new MyGenerator());//errorFillArray.fill(new Integer[5], new MyGenerator());}}interface Generator
{T next();}class MyGenerator implements Generator
{@Overridepublic Integer next() {return 0;}}class FillArray
{public static
void fill(T[] arr, Generator
generator) {for (int i = 0; i < arr.length; i++) {arr[i] = generator.next();}}}
Observe the above Code. In the main method, we create an array of int and Integer respectively. The int throws an exception. Here, the automatic packaging mechanism does not work.
Summary: This chapter mainly discusses the problem that basic types cannot be used for generics.
This chapter is here. Thank you.