Collection (8): generic class, generic method, generic interface
Foreword case
import java.util.ArrayList; import java.util.Iterator; public class GenericDemo1 { public static void main(String[] args) { //Create a List collection object ArrayList list = new ArrayList(); //Add elements to the collection list.add("hello"); list.add(10);//Equivalent to upward transformation, 10 -- int -- Integer list.add("world"); //Get iterator object Iterator iterator = list.iterator(); //Get iterator object while(iterator.hasNext()){ Object next = iterator.next(); String s = (String)next; System.out.println(s); } } }
The results are as follows:
According to the normal writing method, we add some data of different types to the collection, and report an error when traversing ClassCastException:Type conversion exception Why? Because when we store data, we store some String and Integer Type of data, but, When we traverse, the default set only stores String Type of data; But when storing data Didn't tell us we had to save String If only you could tell me which data types can be stored when storing
String[] arr = new String[3];//When creating an array, specify the type of element arr[0] = "hello"; // arr[1] = 20; It is not feasible to add int type java In the collection, the array is imitated. There is also such a practice. When creating the collection, the data type of the element is defined, After creation, the elements added to the collection can only be the data related to the defined data type, and then there is no problem in downward transformation. Such technology, java Generic type
generic paradigm
1, Introduction to the use of generics
1. Overview of generics
The work of specifying data types is advanced to the compilation time, and the data types are specified when creating collections, This approach is a bit like passing data types as parameters. So generics have another name: parameterized types
2. Generic definition format
Define format: <Reference data type>,stay API Medium is<E> Note: data types in angle brackets can only be reference data types,<E>Add after the class when creating the object
Format case:
ArrayList<String> list = new ArrayList<String>(); JDK1.7 Type inference is then performed automatically So the back<String>Medium String Yes or no, it is recommended to add
When creating an object, generics are added to the iterator //Get iterator object Iterator<String> iterator = list.iterator();
When generics are not used, errors will not be reported when adding elements of different types, but only when transforming downward; When using generics, errors will be reported when adding elements and writing code. Errors will be reported in advance for us to change
3. Benefits of generics
After adding generics (1)Advance the problems we encountered during the previous run to the compilation time (2)There is no need to cast types, and you can call methods of element types (3)Optimized code to eliminate unnecessary yellow warning lines
4. Usage scenarios for generics
Through observation API It is found that generics can appear on classes, interfaces and methods, and see some similarities and differences<E>, In general, generics appear in collections that are mostly used
2, Application of generics
1. Generic class
Generic class:Define generics on the class (add after the class name)<Variable name>) format:public class Class name<Generic type 1,...> be careful:Generic type must be a reference type
there<>The content only represents a parameter data type, which is a variable, Since it is a variable, it conforms to the naming rules of variables, and can be any name that conforms to the naming rules of identifiers
Use of generic classes
//Step 1: define a generic class class GenericTool1<T> { private T obj; public T getObj() { return obj; } public void setObj(T obj) { this.obj = obj; } } //Step 2: Test generic classes public class GenericTest1 { public static void main(String[] args) { /* If the previously defined class does not add generics, the default is Object type GenericTool1 gt1 = new GenericTool1(); When adding elements, the type can be arbitrary gt1.setObj("hello"); gt1.setObj(20); gt1.setObj(12.34); gt1.setObj(new Student()); */ //Create an object of a generic class GenericTool1<String> gt = new GenericTool1<>(); //Call the setObj() method to add an element gt.setObj("hello"); //gt2.setObj(20); After defining generics, you cannot add elements of different types //Call the getObj() method to get the element String obj = gt.getObj(); System.out.println(obj); } } The results are as follows: hello Process finished with exit code 0
2. Generic method
Generic methods: define generics on methods format:public <generic types > Return type method name(generic types .) Example: public<T> void show(T t){}
(1) When generics are not used, it is normal to write a class to define member methods
//Define a class public class GenericTool2 { public void show(String s){ System.out.println(s); } public void show(int i){ System.out.println(i); } public void show(double d){ System.out.println(d); } } //Define a test class public class GenericTest2 { public static void main(String[] args) { //Create an object of class GenericTool2 gt1 = new GenericTool2(); //Call the show method in the class and assign a value gt1.show(10); gt1.show("hello"); gt1.show(12.34); } } The results are as follows: 10 hello 12.34 Process finished with exit code 0
When we do not use generics, when assigning values in the test class, we must assign values according to the defined member method parameter types,
When you need to assign many types, you need to define many member methods, which is very troublesome.
(2) When using a generic class, the member method parameter types of the generic class are consistent with those of the generic class
When assigning many types, there is no need to define many member methods
//Define a generic class class GenericTool2<T> { //Define member methods with T-type parameters public void show(T t){ System.out.println(t); } } //Define a test class public class GenericTest2 { public static void main(String[] args) { GenericTool2 gt1 = new GenericTool2(); //Generic classes are defined earlier. You can assign different types at will by assigning values here gt1.show(10); gt1.show("hello"); gt1.show(12.34); } } The results are as follows: 10 hello 12.34 Process finished with exit code 0
(3) When a generic class is defined, the member method parameter types of the generic class are consistent with those of the generic class,
What happens if generics are added when creating objects in the test?
//Define a generic class class GenericTool2<T> { //Defining generic member methods public void show(T t){ System.out.println(t); } } //Define a test class public class GenericTest2 { public static void main(String[] args) { //Add generics when creating generic class objects GenericTool2<String> gt2 = new GenericTool2<>(); gt2.show("hello"); //gt2.show(20); When a generic type is added when creating an object, an error will be reported when assigning an int type //To assign an element of type int, you must create another object of type int GenericTool2<Integer> gt3 = new GenericTool2<>(); gt3.show(20); } } The results are as follows: hello 20 Process finished with exit code 0
It can be seen that when a generic class is defined, the member method parameter types of the generic class are consistent with those of the generic class,
Generics are also added when creating objects in the test,
When assigning different types, you need to create a lot of objects, which is very troublesome
If there is no generic type on the defined class, can the method pass parameters freely?
The answer is yes, but generic methods are needed at this time
Moreover, the test class cannot have generics when creating objects, otherwise an error will be reported
//Define a class public class GenericTool2 { //Defining generic member methods public<T> void show(T t){ System.out.println(t); } } //Define a test class public class GenericTest2 { public static void main(String[] args) { //create object GenericTool2 gt = new GenericTool2(); //After defining a generic method, any type of parameter can be passed in during assignment gt.show("hello"); gt.show(20); gt.show(true); } } The results are as follows: hello 20 true Process finished with exit code 0
3. Generic interface
Generic interface: define generics on interfaces Format: public interface Interface name<Generic type 1...>
Case:
//Define a generic interface, and the method parameters in the interface are consistent with the interface public interface GenericTool3<T> { public abstract void show(T t); }
//Define a class to implement a generic interface, and add generics to the class that implements the interface public class GenericTool3Impl<T> implements GenericTool3<T>{ //Override abstract methods in interfaces @Override public void show(T t) { System.out.println(t); } }
//Testing of generic interfaces public class GenericTest3 { public static void main(String[] args) { //The interface cannot be instantiated. Its implementation class needs to be new GenericTool3Impl<String> sgt1 = new GenericTool3Impl<>(); sgt1.show("hello"); } }
The results are as follows:
hello Process finished with exit code 0