Java basics-generic 1 and java Basics

Source: Internet
Author: User

Java basics-generic 1 and java Basics

 

The use of generics can make the type name as a parameter in the class or interface definition, just like a common parameter, so that the defined type is more universal.

Advantages of generics:

  • Strict type check for compilation

The java compiler is more rigorous in checking the type of generic code and can detect some runtime errors in common code.

  • Eliminate type conversion
// The following code does not use generics. You need to convert the type List = new ArrayList (); list. add ("hello"); String s = (String) list. get (0); // The use of generics does not apply to type conversion List <String> list = new ArrayList <String> (); list. add ("hello"); String s = list. get (0); // no cast

 

  • Enable programmers to implement common algorithms

By using generics, a type of different types can be used for general operations.

1. Generic

Generic is a type parameterized class or interface.

1.1 generic declaration

General generic declarations are similar to the following:

class name<T1, T2, ..., Tn> { /* ... */ }

 

Parameters in angle brackets are type parameters separated by commas. type parameters can be any type of any non-basic data type. The generic interface declaration is similar to the above generic type.

1.2 generic parameter naming

Generally, the name of a generic type parameter is a single uppercase letter, which is separated from the variable name.

The most common parameter type parameter name is:

  • E-element (applied by java Collection framework)
  • K-Key
  • N-Number
  • T-type
  • V-Value
  • S, U, V, etc.-second, third, fourth type

These names are widely used in javaSE APIs.

1.3 call and instantiate generic

To reference a generic type, you must first make a generic call, as shown below:

// Input type parameter. The following is String as the type parameter ArrayList <String> list;

 

The above code can be seen as a call method, but it is a type parameter. This process is called a parameterized type. The syntax for instantiating a generic type is as follows:

// Complete ArrayList <String> list = new ArrayList <String> () in one step ();

 

1.4 Diamond

After Java 7, as long as the compiler can judge the type parameter based on the context of the Code, it can leave the type parameter of the generic constructor empty (<>) because the empty angle brackets are like diamond, therefore, the informal form of diamond can be abbreviated:

// Note that the parameters in the constructor have omitted ArrayList <String> list = new ArrayList <> ();
1.5 parameterized type as type parameter

Generic Type parameters can also be generic parameters, such:

// Omit the constructor type parameter ArrayList <List <String> list = new ArrayList <> ();

 

2. Definition of the original type 2.1

The original type is a generic type without a type parameter. For example, declare an original type:

// ArrayList is a generic type, so the List variable is of the original type ArrayList list = new ArrayList ();

 

Legacy of the old java version of the original type, because many API classes, such as collection classes, were not generic before JDK 5, in order to be backward compatible, assigning a parameterized generic object to an original type is allowed:

Box<String> stringBox = new Box<>();Box rawBox = stringBox;               // OK

 

However, if a primitive type is assigned to a parameterized generic type, the compiler will give a warning:

Box rawBox = new Box (); // rawBox is the original Box type of Box <T> <Integer> intBox = rawBox; // warning: unchecked conversion

 

If you use the original type to call the generic method of the formation, you will also receive a warning:

Box<String> stringBox = new Box<>();Box rawBox = stringBox;rawBox.set(8);  // warning: unchecked invocation to set(T)

 

Compiler warning indicates that the original type bypasses the type check and leaves the risk of possible errors to the runtime, so try not to use the original type.

2.2 error message not checked

As mentioned earlier, when generics and traditional syntaxes are mixed, you will encounter the following warning messages:

Note: Example. java uses unchecked or unsafe operations.

Note: Recompile with-Xlint: unchecked for details.

The term "unchecked" (unchecked) indicates that the compiler does not have sufficient information about the type to perform the check to ensure the type is secure. By default, the compiler generates a warning that no check is performed, but a prompt is displayed, if you want to enable the unchecked warning, add the parameter during compilation.-Xlint: unchecked.

If you want to completely disable the unchecked warning, you can add parameters during compilation.-Xlint:-unchecked(Note the difference from the preceding parameters) or use annotations.@ SuppressWarnings ("unchecked ").

3 generic Method

Generic methods refer to methods that introduce their own parameter types, just like generic type parameters. However, the use of method type parameters is limited to methods. Static and non-static generic methods can be defined, and generic constructors can also be defined.

The syntax of the generic method contains the type parameters in square brackets before the return type of the method. Of course, non-generic classes can also contain generic methods.

The following example illustrates the declaration of generic methods:

Public class Util {// The following method is the generic method public static <K, V> boolean compare (Pair <K, V> p1, Pair <K, V> p2) {return p1.getKey (). equals (p2.getKey () & p1.getValue (). equals (p2.getValue () ;}} public class Pair <K, V> {private K key; private V value; public Pair (K key, V value) {this. key = key; this. value = value;} public void setKey (K key) {this. key = key;} public void setValue (V value) {this. value = value;} public K getKey () {return key;} public V getValue () {return value ;}}

 

The complete syntax for calling generic methods is:

// The following statement uses the Pair class defined above <Integer, String> p1 = new Pair <> (1, "apple"); Pair <Integer, string> p2 = new Pair <> (2, "pear"); boolean same = Util. <Integer, String> compare (p1, p2 );

 

Of course, if you compile it to deduce the type, you can omit the type parameter of the generic method:

Pair<Integer, String> p1 = new Pair<>(1, "apple");Pair<Integer, String> p2 = new Pair<>(2, "pear");boolean same = Util.compare(p1, p2);

 

4. Restricted parameter range

Sometimes you may need to limit generic type parameters. For example, a generic type parameter can only be a Number, a subclass, or an inherited class.

The limitation of declared type parameters is to keep up with the extends keyword after the parameter name, and then keep up with its upper limit, such as Number. Here extends generally refers to the extends of the class and the implements of the interface ., Such as the declaration of the following method:

public <U extends Number> void inspect(U u){        System.out.println("T: " + t.getClass().getName());        System.out.println("U: " + u.getClass().getName());    }

 

A type parameter can have multiple limits, that is, the extends keyword is followed by multiple upper limits, separated by symbols:

class D <T extends A & B & C> { /* ... */ }

 

5 generic, inheritance, and subtypes

In java, a type Object can be assigned to another type of variable. If the two types are compatible, for example, an Integer Object can be assigned to a variable of the type Object. In object-oriented terms, this is a relationship called "yes". For example, if the Integer type is an Object type, the assignment is allowed. The same is true for passing parameters of methods including generic methods, as shown in figure

// The element type of the ArrayList type that is parameterized as follows is NumberArrayList <Number> list = new ArrayLIst <Number> (); // The parameter type of the add method is also Number, you can also use its subclass Integer instance list. add (new Integer (10 ));

 

However, the Subtype Relationship of the generic type is different from that of the common type, as shown in:

Arrows indicate child-type relationships. For example, Integer is the child type of Number, while Box <Integer> is not the child type of Box <Number>, the common parent type of Box <Integer> and Box <Number> is Object.

You can inherit or implement a generic type to become a subtype of the generic type. The relationship between the type parameters of a class or interface is determined by the extends and implements statements.

For example, in the Collection class, ArrayList <E> implements List <E> and List <E> inherits Collection. Therefore, ArrayList <String> is a subtype of List <String>, list <String> is the child type of Collection <String>. This inheritance relationship is retained as long as the type parameter is not changed:

Now you can customize a new interface that inherits the List interface:

// Note interface PayloadList <E, P> extends List <E> {void setPayload (int index, P val );...}

 

The parameterized type is subject to the following relationship:

 

Related Article

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.