What is Java's generics?Type parameterizationThis type includes the method parameters and return values, that is, the variable is replaced with the variable where the type is originally determined, and the type determination time is delayed backward.
I have learned the concept of "overload" before. What is overload? For example:
Public class Test {// process the void receive (int I) {System. out. println ("Received one int data"); System. out. println ("I =" + I);} // process floating point data void receive (float f) {System. out. println ("Received one float data"); System. out. println ("f =" + f);} // process String data void receive (String s) {System. out. println ("Received a String"); System. out. println ("s =" + s );}}
The three methods in the preceding class have the same processing logic, but the parameter types are different. When a method is called, the program calls the method of the corresponding parameter based on the parameter type. This is the parameter overload, allowing the class to process different data types in a unified way.
What is the relationship between generics and overloading?
Generics and overloading handle multiple data types from different perspectives. Generics can be used more widely and can be used for methods, interfaces, and classes. So let's take a look at how to implement the Test class above with generics?
public class Test
{void receive(T t) {System.out.println("Received one "+t.getClass().getName()+" data");System.out.println("t="+t);}public static void main(String[] args){Test
test=new Test
();test.receive("abc");Test
test1=new Test
();test1.receive(1);}}
We found that in a generic application, we replaced the specific type parameter with the variable T. We can wait until the actual call to determine the type of the parameter, which greatly reduces the amount of code, and T can be any type in java (including basic type and object type ). In fact, there is no new knowledge here, but on the basis of the function, the types of incoming data and output data (return values) are also parameterized. The following is an example of the return value of a method that uses generics:
public class TestGenetic
{public Hashtable
table=new Hashtable
();public void put(K k,V v){table.put(k, v);}public V get(K k){return table.get(k);}public static void main(String[] arg){TestGenetic
test=new TestGenetic
();test.put("001", "abc");test.put("002", "def");String str=test.get("001");System.out.print(str);}}
The Return Value of the get method is also generic, so the application is more flexible. Of course, the T, K, and V used in the above Code are only equivalent to the variable name and can be replaced by any letter.