Java Collection
One drawback of the Java collection is that when an object is "thrown into" the collection, the collection will "forget" the data type of the object, and when the object is fetched again, the object's compilation type becomes object type (its runtime type is unchanged).
The design is so designed because the programmer of the collection does not know what type of object we are going to use it to hold, so it is very versatile. However, this brings up the following two questions:
Set pairs are not limited to element types, such as a collection can hold an Apple object can also save a banana object;
Because the object has lost its state information after it enters the collection, it needs to be forced to cast the type.
Look at the following program:
List List = new ArrayList ();
List.add (1);
List.add (2);
List.add ("No. fifth");//accidentally inserting a string
For (Object object:list) {
//Take out the "No. Fifth" Times ClassCastException
Integert = (Integer) object;
}
The above is an error that occurs when a collection is not using generics, so when we use generics, the error is avoided, for example:
list<integer>list = newarraylist<integer> ();
List.add (1);
List.add (2);
List.add ("fifth");//Insert string, causing compilation error
1. Understanding Generics
The parameterized type of Java is called Generics, which allows us to specify the type of the collection element when the collection is created, which can only hold elements of its specified type.
Generics allow the use of type parameters when defining classes, interfaces, and methods, which are dynamically specified when declaring variables, creating objects, and invoking methods, arguments. For example:
//Define an interface
Interface money<e>{
eget (intindex);
Boolean Add (e e);
}
//define a class
Public classapple<t>{
private T info;
Public Apple (T info) {
this.info = info;
}
Public T GetInfo () {
return this.info;
}
Public void SetInfo (T info) {
this.info = info;
}
Public static void Main (string[] args) {
Apple<string>ap1 = newapple<string> ("Little Apple");
System.out.println (Ap1.getinfo ());
apple<double>ap2 = newapple<double> (1.23);
System.out.println (Ap2.getinfo ());
}
}
It is important to note that type parameters are not allowed in the declaration and initialization of static methods, static initialization blocks, or static variables. Because no matter which type argument is passed in for a generic type parameter, for Java they are treated as if they were the same class and only occupy a single chunk of memory in memory. Regardless of the actual type parameters of generics, they always have the same class at run time (class), for example, the following program will output true.
list<string> l1 = new arraylist<string> ();
list<double> L2 = new arraylist<double> ();
System.out.println (l1.getclass () = = L2.getclass ());
2. Type wildcard characters
If we want to define a method, the parameter of the method is a set parameter, but the element type of the set parameter is indeterminate. You might think of the following two definition methods:
Public void Test1 (List l) {}
Public void Test2 (list<object> l) {}
Test1 can be used, but will report a generic warning;
Test2 cannot be used when passing in non-list<object>, it will be reported that "test2 (list<object>) does not apply to parameters (list<string>)";
To represent the parent class of various generic lists, we need to use the type wildcard character, which is a question mark (? ), passing a question mark as a type argument to the list collection, writing list<?> then we can define the method above:
public void Test3 (list<?> l) {}
At this point we can pass in the list with any element type as a set parameter, even if it is a custom class.
But there's a special situation where we don't want this list<?> to be the parent of any generic list, just to indicate that it is the parent of a class of generic lists, for example we have a circle class (circle), a rectangle class (Rectangle), These two classes inherit the shape abstract class, so we can design this:
Public classtest{
Public static void Main (string[] args) {
list<circle>list = newarraylist<circle> ();
List.add (New Circle ());
CANVASC = Newcanvas ();
C.drawall (list);
}
}
Abstract classshape{
Public abstract void Draw (Canvas c);
}
class canvas{
Public String toString () {
return "Canvas";
}
Public void Drawall (list<? extends shape> shapes) {
For (Shape shape:shapes) {
Shape.draw (this);
}
}
}
class Circle extends shape{
Public void Draw (Canvas c) {
System.out.println ("Draw a circle on the canvas" + C + ");
}
}
class Rectangle extends shape{
Public void Draw (Canvas c) {
System.out.println ("Draw a rectangle on the canvas" + C + ");
}
}
list<? Extends Shape> is an example of a restricted wildcard, where the question mark (?) Represents an unknown type, just like the wildcard character you see earlier. But the unknown type here must be a shape's subclass or shape itself,
So we can refer to shape as the upper limit of this wildcard character.
It is important to note that because you do not know the specific type of the restricted wildcard, you cannot add the object of the Shape object or its subclasses to the generic collection, for example, the following code will report a compilation error:
public void Drawall (list<? extends shape> shapes) {
Compile errors are reported here
Shapes.add (New Rectangle ());
}
Java generics not only allow you to set an upper limit when using wildcard parameters, but you can also set an upper limit when defining a type parameter, which is used to indicate that the actual type passed to the type parameter is either the upper bound type or a subclass of the upper bound type, for example:
Public class Apple<t extends number>{
T ColT;
Public static void Main (String[]args) {
apple<integer> ai = new apple<integer> ();
apple<double> ad = new apple<double> ();
//The following code throws a compilation error because the String class is not a subtype of number
apple<string> as = new apple<string> ();
}
}
3. Generic method
The so-called generic method is to define one or more type parameters when declaring a method. The usage format of a generic method is as follows:
Modifier <T,S> return value type method name (formal parameter list) {
Method body
}
Comparing the format of the above method with the format of the common method, it is not difficult to find that the method signature of the generic method is more than the method signature of the ordinary method, the type parameter declaration is enclosed with angle brackets, and the multiple type parameters are separated by commas (,). All type parameters are declared between method method modifiers and method return value types.
For example, we'll write a method that adds all the elements of an object array to a collection collection:
static <T> void Fromarraytocollection (t[] a,collection<t> c) {
For (T t:a) {
C.add (t);
}
}
The above method is correct, there is no error, but in our actual use of the process, we can only add elements in the array collection, want to add a collection element in another collection, the above method does not apply. So can we improve the way we do it?
static <T> void Fromarraytocollection (collection<t> a,collection<t> b) {
For (T t:a) {
B.add (t);
}
}
Public static void Main (string[] args) {
list<string> a = new arraylist<string> ();
list<object> B = new arraylist<object> ();
Fromarraytocollection (A, b);
}
Obviously, when we call Fromarraytocollection, a compilation error is thrown because the compiler cannot accurately infer the type of the type parameter in the generic method, not whether it should be string or object. To avoid this error, you can change the method to this:
static <T> void Fromarraytocollection (collection<? extends t> A, collection<t> b) {
For (T t:a) {
B.add (t);
}
}
Public static void Main (String[]args) {
list<string> a = new arraylist<string> ();
list<object> B = new arraylist<object> ();
Fromarraytocollection (A, b);
}
In the above method, the previous parameter type of the method is changed to Collection< Extends T> this takes a representation of the type wildcard, as long as the element type in the previous collection collection of the method is a subclass of the element type in the latter collection collection.
4. The difference between generic methods and type wildcard characters
A generic method can be used most of the time instead of a type wildcard character. For example, the definition of two methods in the Java Collection interface:
Public Interface collection<e>{
boolean containsall (collection<?>c);
Booleanaddall (collection<? extends e> c);
... ..
}
The parameters of the two methods in the above collection are in the form of a wildcard, or in the form of a generic method, as follows:
Public Interface collection<e>{
<T> boolean containsall (collection<t> c);
<t extends E> boolean addall (collection<t> c);
... ..
}
The above method uses the <textends e> generic form, when defining the type parameter when setting the upper bound (where E is the type parameter defined in the collection interface, where e can be used as a normal type).
The type parameter T in the above two methods is used only once, and the only effect that the type parameter T produces is that it can pass in different actual types at different call points. In this case, wildcard characters should be used: wildcards are designed to support flexible subclasses.
A generic method allows a type parameter to be used to represent a type dependency between one or more parameters of a method, or a method returns a type dependency between a value and a parameter. If you do not have such a type dependency, you should not use a generic method.
Generics for Java