Generic type
The parameter type of a generic type must be a reference type
such as arraylist<int> list = new arraylist<int> (); Error
arraylist<integer> list = new arraylist<integer> (); That's right
List.add (5); Proper automatic packing (packing) mechanism
int i = list.get (0); correctly, if the element is a wrapper type, such as Integer,double,character, you can assign the element directly to a variable of the basic type. This process is called the automatic unboxing mechanism.
Importjava.util.ArrayList; Public classGenericstack<e> { Privatearraylist<e> list =NewArraylist<e>(); Public BooleanIsEmpty () {returnList.isEmpty (); } Public intGetSize () {returnlist.size (); } PublicE Peek () {returnList.get (GetSize ()-1); } Publice pop () {e o= List.get (GetSize ()-1) ; List.remove (GetSize ()-1); returno; }
public void push (E o) {
List.add (o);
}
Public String toString () {
Return "stack:" + list.tostring ();
}
}
Genericstack the constructor form after erasing the parameter type is Genericstack (), not genericstack<> ();
Generic class if you have more than one parameter type, place multiple arguments in one angle bracket, such as <E1,E2,E3>.
You can define a class or interface as a subtype of a generic class or generic interface, such as the Java API, where the Java.lang.String class implements the comparable interface: public class String implements comparable <String>;
Generics can be specified as a subtype of another type (or generic), such that a generic type is called a restricted
public class boundedtypedemo{
public static <e extends Geometricobject> boolean Equalarea (e Object1, E object2)
{
return Object1.getarea () = = Object2.getarea ();
}
}
Note: The location of the generic type placement should precede the return type of the method (defining a generic method) or after the class name (when defining a generic class)
You can use the primitive types of generics (Generic) without specifying a specific type. Such as:
Genericstack stack = new Genericstack (); Equivalent to
genericstatck<object> stack = new genericstack<object> ();
This genericstack generic class with no type parameters is called the original type. The original type can be backwards compatible with earlier versions of Java. such as the comparable type
Three different forms:
? , non-restricted wildcard, equivalent to? Extends Object
? Extends T, restricted pass, denotes subclasses of T or T
? Super T, lower bound, indicates the parent type of T or T
Java Basic Knowledge Generics