Java Generics basic usage

What is a generic Java (Java Generics)

First we look at the following code:

List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

By defining <String> Next to Type List, the compiler will be able to know where the object List collection should be String. When the compiler at compile the code, it can help us to do type checking. If we add objects to the List of non-String class, the compiler will report an error.

If the object is stored in our collection List is Double, Float or Integer, we only need to modify the generic type definition.

List<Double> doubleList = new ArrayList<>();
List<Float> floatList = new ArrayList<>();
List<Integer> integerList = new ArrayList<>();

It can be seen, only one write List implementation class code (the ArrayList), it can be reused in different types of objects on. And the compiler will type checking at compile time for us .

This is the Java generics.

Generic method and generic class Java (Java Generic Class and Method)

By following code, we can see an example of a generic class and generic methods.

// 泛型类定义
class Container<T> {
	// 泛型定义的类变量
	private T item;
	
	// 泛型方法: 接受泛型参数
	public Container (T item) {
		this.item = item;
	}

	// 泛型方法: 接受泛型参数
	public void setItem (T item) {
		this.item = item;
	}

	// 泛型方法: 返回泛型对象
	public T getItem () {
		return this.item;
	}
}

As can be seen from the above code, we simply will define the type of local variables replaced with generic T , we can make our class enjoy flexible benefits brought about by the generics.

Java generic interface (Java Generic Interface)

Use Java generic interface with Java generic class is very close, but remember that (implementing classes) should be declared in the class that implements a generic class .

// 泛型接口
public interface Speak<T> {
    void speak(T speech);
}

// 实现类也需要声明泛型 <T>
public class Person<T> implements Speak<T> {
    public void speak(T speech) {
        System.out.println(speech);
    }
}

public static void main(String[ ] args) {
    Person<String> p = new Person<>();
    p.speak("Hello");
}

You will have the opportunity I will publish a more detailed analysis of Java another generic article.

Author still learning, if there is something wrong, please point out and contain, thank you!

Author: David Chou (Vancouver SFU computer student)

Published 14 original articles · won praise 8 · views 2208

Guess you like

Origin blog.csdn.net/vandavidchou/article/details/102566069