Java generic type basis

Why use generics?

Not using generics:

// 创建列表类
List list = new ArrayList();
// 添加一个类型为 String 的列表元素
list.add("hello");
// 强制转换为 String 类型,再赋值给类型为 s 的引用变量
String s = (String) list.get(0);

The use of generics:

// 创建泛型类,<String> 为类型参数
List<String> list = new ArrayList<String>();
// 添加一个类型为 String 的列表元素
list.add("hello");
// 这里不需要强制类型转换
String s = list.get(0);

Benefits: achieve universal generic algorithms, processing different types of collections, you can customize the type, type-safe, easy to read.

Generic type

A generic type is of a type parameter (<parameter type>) generic class or interface.

A simple Box class

public class Box {
    private Object object;

    public void set(Object object) { this.object = object; }
    public Object get() { return object; }
}

Box class methods accept or return an object, in addition to the basic types you can pass any object. If passed an Integer Integer and want to get, but the String object passed in error, it will lead to runtime errors at compile time can not check how the class is used.

Box class generic version

Generic type definition format:

class name<T1, T2, ..., Tn> { /* ... */ } //T1, T2, ..., Tn为类型参数

Type parameter (also known as type variable) with the back of the class name, the type of parameter in the angle brackets (<>) and (T1, T2, ..., and Tn),

The revised generic Box class:

/**
 * Box 类的泛型版本
 * @param <T> 类型的值被装箱
 */
public class Box<T> {
    // T 表示 "类型"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

The above code, all Object types Box class type is replaced by T, a variable may be any type of non-specified basic types: the type of any class, any interface type, an array of any type, or even any other types of variables.

Generic technology can also achieve a common generic interface.

Type parameter naming convention

Conventionally, the type of a parameter called single capital letters. This is a known variable naming conventions in stark contrast, do so with good reason: Without this agreement, it is difficult to distinguish between the types of variables and ordinary class or interface name.

The most common type Parameter name:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

Call and instantiate a generic type

A particular type of alternative types of variable T can instantiate a generic type, for example:

Box <Integer> integerBox = new Box <Integer>();

Common type of call is generally referred to as "parameterized type."

As usual use newthe keyword to instantiate, but placed between the class name and the parentheses <Integer>:

In Java SE 7 and later releases, as long as the compiler can determine or infer the type of parameters, it can be set by a null type parameter (<>) Alternatively call type depending on the context parameters required for generic class constructor. E.g:

Box<Integer> integerBox = new Box<>();

Multi-parameter type

Generic class can have a plurality of types of parameters. For example, to achieve universal interface OrderedPair general class Pair:

public interface Pair<K, V> {
    public K getKey();
    public V getValue();
}

public class OrderedPair<K, V> implements Pair<K, V> {

    private K key;
    private V value;

    public OrderedPair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey()   { return key; }
    public V getValue() { return value; }
}

The following statement creates two instances OrderedPair class:

Pair <String,Integer> p1 = new OrderedPair <String,Integer>(“Even”,8);
Pair <String,String> p2 = new OrderedPair <String,String>(“hello”,“world”);

The new OrderedPair <String,Integer>code will be instantiated as a string K, V is instantiated as an integer. Thus, the parameter type constructor OrderedPair respectively String and Integer. Since the automatic packing, and the String int passed to the class is effective.

As mentioned above, since the Java compiler can OrderedPair <String,Integer>infer K and V type declaration, it is possible to use the following abbreviations:

OrderedPair <String,Integer> p1 = new OrderedPair <>(“Even”,8);
OrderedPair <String,String> p2 = new OrderedPair <>(“hello”,“world”);

Parameterized type

You can also replace the type of parameters parameterized type (ie List) (ie, K or V). For example, using OrderedPair <K,V>the example:

OrderedPair <String,Box <Integer>> p = new OrderedPair <>(“primes”,new Box <Integer>(...));

Primitive types

It is the original type parameter without any type of generic class or interface name.

For example, given a generic class Box:

public class Box<T> {
    public void set(T t) { /* ... */ }
    // ...
}

To create a parameterized type, provide the actual type parameters for the formal type parameter T:

Box<Integer> intBox = new Box<>();

If the actual type parameter is omitted, it will create a Box<T>primitive type:

Box rawBox = new Box();

Therefore, Box is a generic Box<T>primitive types. However, non-generic class or interface type is not a primitive type.

In many prior JDK5.0 API (such as the Collections class) are not general for backward compatibility, it allows for the assignment of parameterized types to their original type:

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

However, the original type is assigned to a parameterized type, the compiler will issue a warning:

Box rawBox = new Box();           // rawBox 是 Box<T> 的原始类型
Box<Integer> intBox = rawBox;     // warning: unchecked conversion

If you use the original type to call the generic method defined in the appropriate generic type, you will also receive a warning:

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

The warning displays the original bypass the generic type of type checking, unsafe code will capture postponed until runtime. Therefore, you should avoid using primitive types.

Guess you like

Origin www.linuxidc.com/Linux/2019-06/158977.htm