Java Generics Introduction

Source: Internet
Author: User

First, the purpose of the pan-

The Java collection does not know what type of object we need to save, so they design the collection to hold any type of object, as long as it is very versatile. But this also brings two questions:

– The collection has no restrictions on the element type, which can cause problems: for example, to create a collection that can hold only the dog object, but the program can also easily "throw" the Cat object in, so an exception can be thrown. – Because the collection loses state information about an object because it is "thrown into" the collection, the collection only knows that it is in object, so it is often necessary to force type conversions after the collection element is removed. This forced type conversion increases the complexity of the programming and can also cause classcastexception.

Second, use generics in the collection

Using generics in a collection provides the following benefits

– The program can no longer "accidentally" throw other objects into the Strlist collection;

– The program is more concise, and the collection automatically remembers the data types of all the collection elements, eliminating the need to force type conversions on the collection elements. In the following code, "accidentally" throws an integer object "into" the collection.
Import java.util.*;p ublic class listerr{public static void Main (string[] args) {//Create a list collection that only wants to save the string list strlist = new ARR Aylist (); Strlist.add ("Crazy Java Handout"); Strlist.add ("Crazy Android Handout");//"Accidentally" throws an integer object "into" the set Strlist.add (5);     ①strlist.foreach (STR-SYSTEM.OUT.PRINTLN ((String) str). Length ()); ②}}
① "accidentally" throws an integer object "into" the collection
② throws an ClassCastException exception.

Iii. What is a generic type

Generics are allowed to specify a type parameter in a defined class, interface, which is determined when declaring a variable, creating an object (that is, passing in an actual type parameter, or a type argument).

JDK1.5 overrides all interfaces and classes in the collection framework, adds generic support for these interfaces, classes, and allows you to pass in a type argument when declaring a collection variable, creating a Collection object.

Four, generic "diamond" grammar <>

The following code:

list<string> books = new arraylist<String> (); map<string,integer> books = new arraylist<string,integer> ();

The bold code in,<> before Java 7 is mandatory, but it is now possible without bold code. Java automatically infers whether the <> in ArrayList should be string or String,integer.

Now instead:

list<string> books = new Arraylist<> (); map<string,integer> books = new Arraylist<> ();

The first and second sections of code are completely equivalent.

Simple application of generics:

Import java.util.*;p ublic class diamondtest{public static void Main (string[] args) {//Java automatically infers ArrayList <> should be stringlist<string> books = new Arraylist<> () Books.add ("Crazy Java Handout"); Books.add ("Crazy Android Handout");// Traversing the Books collection, the collection element is the string type Books.foreach (Ele-System.out.println (Ele.length ()));//Java automatically infers HashMap <> It should be String, list<string>map<string, list<string>> schoolsinfo = new hashmap<> ();// Java automatically infers that the ArrayList <> should be stringlist<string> schools = new arraylist<> (); Schools.add ("Oblique month Samsung Hole"); Schools.add ("West of the West"); Schoolsinfo.put ("Monkey King", schools);//The Map key is a String type when traversing the map, and value is list<string> Type Schoolsinfo.foreach (key, value)-System.out.println (key +-+ + value);}}

  

Five, in-depth generics

1. Define generic interfaces, classes

Generic declaration used when defining an Apple class

Generic declaration used when defining the Apple class public class apple<t>{//use the T type parameter to define instance variables private T info;public Apple () {}// The T type parameter is used in the following method to define the constructor public Apple (t info) {this.info = info;} public void SetInfo (T info) {this.info = info;} Public T GetInfo () {return this.info;} public static void Main (string[] args) {//Because a String is passed to the T parameter, the constructor argument can only be stringapple<string> a1 = new Apple<> (" Apple "); System.out.println (A1.getinfo ());//Because a double is passed to the T parameter, the constructor argument can only be double or doubleapple<double> a2 = new apple< > (5.67); System.out.println (A2.getinfo ());}}

2. Deriving subclasses from generic types

A1 Inheriting generic classes:

When using a generic class, passing in the String class type public class A1 extends apple<string>{}//correct//using a generic class for the T parameter, there is no actual type parameter passed in for the T parameter, which produces a warning: generic check warning, Using an unchecked or unsafe operation public class A1 extends apple{}//correct//apple class cannot follow type parameter public class A1 extends error

Inherit the Apple class, and T is replaced by a string. Subclasses inherit two methods of string GetInfo () and void SetInfo ().

public class A1 extends apple<string>{//correctly overrides the parent class's method, the return value//is exactly the same as the return value of the parent class Apple<string> public String getInfo () { Return "Subclass" + Super.getinfo ();} /*//The following method is incorrect, overriding the parent class method when the return value type is inconsistent. Inherited from the parent class should be public String getinfo () public Object GetInfo () {return "subclass";} */}

The correct wording is as follows:

public class A2 extends apple{//method public String GetInfo () {//Super.getinfo () method return value is Object type,//So add ToString () Returns a string of type return Super.getinfo (). toString ();}}

3. There is no generic class

Although the Arraylist<string> class can be regarded as a subclass of ArrayList, in fact Arraylist<string> class is indeed a special kind of ArrayList class, this arraylist< The String> object can only add a string object as a collection element.  In fact, the system does not generate a new class file for arraylist<string>, and it does not treat arraylist<string> as a new class. In fact, generics have the same behavior for all of their possible type parameters, allowing the same classes to be treated as many different classes.  In full agreement, the static variables and methods of a class are also shared among all instances, so the use of type parameters is not allowed in static methods, static initialization, or declaration and initialization of static variables. Generic classes are not actually generated in the system, so generic classes cannot be used after the instanceof operator.

Six, type wildcard characters

public void Test (list<object> c) {for (int i=0;i<c.size (); i++)
{
SYSO (C.get (i));
}
}

This code does not appear to have any problems, and the declaration of the method does not have any problems. But the problem is: Call the value of the actual parameter passed in by the method. For example:

Create a List<string> object list<string> strlist = new arraylist<> ();
Call Strlist as a parameter to test
Test (strlist);

Compile the above program, an error occurred.

Failed to apply test (java.util.list<java.lang.object>) in test to java.util.list<java.lang.string>

This means that the List<string> object cannot be used as a List<object> object, that is, the:list<string> class is not a subclass of the List<object> class.

In addition, arrays and generics are different: If Foo is a subtype (subclass or subinterface) of Bar, then foo[] is still the bar[] type, but g<foo> is not a subtype of g<bar>.

seven,? Usage of

In order 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<?> (meaning List of unknown type elements). This question mark (?) is called a wildcard, and its element type can match any type.

In the "Six" program, the

public void Test (list<object> c) {for (int i=0;i<c.size (); i++) {Syso (C.get (i)); }}

Switch

public void Test (list<?  > C) {for (int i=0;i<c.size (); i++) {Syso (C.get (i)); }}

There is no error in compiling again.

In here?   What can be said, is not giving it too much power!! Of course we have our own solution: set the upper limit of the type wildcard

Using list<?>, this form means that the list collection can be the parent class of any generic list. 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.
We need a generic representation that can represent the parent class of all shape generic lists, and in order to meet this requirement, the Java generics provide a restricted generic wildcard character. The following representation of the restricted generic wildcard character: List<?extends shape>
Defining an abstract class Shapepublic abstract class Shape{public abstract void Draw (Canvas c);}

  

/define a subclass of Shape Circlepublic class Circle extends shape{//implement a paint method to print a string to simulate the drawing method implementation public void Draw (Canvas c) { System.out.println ("Draw a circle on canvas + C +");}}

  

Define a subclass of Shape Rectanglepublic class Rectangle extends shape{//implement a paint method to print a string to simulate a drawing method to implement public void Draw (Canvas c) { System.out.println ("Draw a rectangle on the canvas" + C + ");}}

The above defines three shape classes, the sharp abstract parent class, the Circle class and the rectangle class inheriting the abstract class sharp.

The following defines a canvas class that has different shapes for the canvas class.

Import java.util.*;p ublic class canvas{//draw multiple shapes on the canvas at the same time public void Drawall (list< shape> shapes) {for Shape s:shapes {S.draw (this);}} public static void Main (string[] args) {list<circle> circlelist = new arraylist<circle> (); Canvas c = new canvas ();//Because list<circle> is not a list<shape> subtype,//So the following code throws a compilation error C.drawall (Circlelist);}}

Modify the following:

Import java.util.*;p ublic class canvas{//draw multiple shapes on the canvas at the same time, using the restricted generic wildcard public void Drawall (list<? extends shape> Shapes) {for (Shape s:shapes) {S.draw (this);}} public static void Main (string[] args) {list<circle> circlelist = new arraylist<circle> (); Canvas c = new canvas ();//Since list<circle> is not a list<shape> subtype, wildcard characters are used//So the code below is correct c.drawall (circlelist);}}

There is no error in this piece of code.

Java generics not only allow you to set the upper type limit when using wildcard parameters, but you can also set an upper limit when defining a type parameter, which means that the actual type that is used to create the type parameter must be the upper bound type, or subclass of the upper bound type. For example:
public class Apple<t extends number>{t col;public static void Main (string[] args) {apple<integer> ai = new APPL E<> (); apple<double> ad = new apple<> ();//The following code causes a compilation exception, and the following code attempts to pass the string type to the T parameter//But the string is not a subtype of number, so a compilation error is raised. <String> as = new apple<> ();//①}}

viii. generic methods

It is also possible to define a type parameter when defining a class, an interface that does not use a type parameter, but to define the method itself, JDK1.5 also provides support for generic methods.

The syntax format for a generic method is:

Modifier <t, s> return value type method name (formal parameter list)

{

Method body ...

}

The method signature of a generic method is more of a type parameter declaration than a method signature of a normal method, a type parameter declaration is enclosed in angle brackets, and multiple type parameters are separated by commas (,), and all type parameter declarations are placed between the method modifier and the method return value type. Unlike a generic parameter in a class or interface, a generic parameter in a method does not need to explicitly pass in the actual type parameter, because the compiler infers the value of the type parameter based on the argument. It usually infers the most straightforward type parameters.

Nine, the difference between the generic method and the type wildcard character

A generic method can be used in place of a type wildcard for a large time.

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. 10. Set the lower limit of the wildcard characterThe Java Collection Framework Treeset<e> has a constructor that also uses this syntax for setting the lower bound of the wildcard character as follows: TreeSet (COMPARATOR&LT;? Super E> C) 11. Erase and convertIn strict generic code, classes with generic declarations should always take type parameters. However, in order to be consistent with old Java code, it is also permissible to not specify a type parameter when using a class with a generic declaration.  If a type parameter is not specified for this generic class, the type parameter is referred to as a raw type, which defaults to the first upper bound type specified when the parameter is declared. When you assign an object with generic information to another variable that does not have generic information, all type information between the angle brackets is thrown away. For example, if a list<string> type is converted to list, the list's type check on the collection element becomes the upper bound of the type variable (that is, object), which is erased.

...... Cond

Java Generics Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.