Generics are important in both real-world development and interviews, so let's talk about it today.
1, what is a generic type
The essence of generics is to control the type of formal parameter restrictions by the different types specified by generics for parameterized types.
Give me an example!
We want to define a set that can only hold integers, how to write?
List List = new ArrayList ();
Is that right? Not really, so we can add the task data type to the list
So this time, the solution is to use generics, so you can write
list<integer> list = new arraylist<> ();
With parameterized types, you can limit the types that list can add
2, generic feature, valid only for compilation period, invalid during runtime (generic erase)
Let's see if these two collections are of the same type?
List List1 = new arraylist<> ();
List list2 = new arraylist<> ();
Obviously, during compilation, two collections have a good control over the data types that are added.
However, during run time, this type is erased. Let's do an experiment and get this conclusion.
public static void Main (string[] args) {
Listlist1 = new arraylist<> ();
List list2 = new arraylist<> ();
System.out.println (list1.getclass () = = List2.getclass ());
}
Can try the results, I packed the tickets, the result is true
3, attention.
A generic parameter type can only be a reference type, not a basic data type, such as an int
4, use of generics
4.1 Generic class
public class Generictest {
public static void Main (string[] args) {
GENERICCLASSG1 = new genericclass< ();
G1.setkey (1);
System.out.println (G1.getkey ());
}
}
Class genericclass{
Private T key;
public void Setkey (T key) {
This.key = key;
}
Public T GetKey () {
return this.key;
}
}
4.2 Generic interface
Interface genericinterface{
Public T getNext ();
}
Java core technology -01-talk about generics