Explanation of common tool classes in Java generics

  • 2021-07-10 19:59:03
  • OfStack

1. Generics Overview

1. Background

Before the addition of generics in Java, generic programming was implemented using inheritance.
Disadvantages:

A forced type conversion is required
You can add any type of object to the collection, which is risky

2. Use of generics


List<String> list=new ArrayList<String>();

3. Polymorphism and generics


class Animal{}
class Cat extends Animal{}
List<Animal> list=new ArrayList<Cat>(); // This is not allowed, and the type declared by the variable must match the type passed to the actual object. 

Other examples of errors:


List<Object> list=new ArrayList<String>();
List<Number> number=new ArrayList<Integer>();

4. Generic content

Generics as method parameters Custom generic class Custom generic methods

2. Generics as method parameters

When generics are used as parameters, if the parameters are multiple subclasses, you can use (List) < ? extends Parent Class > xxx). In this case, the parent class and its children can be passed as arguments when the method is called.
One more: (List < ? Class super > xxx). In this case, the class and its superclass (parent class).

3. Customize generics


public class NumGeneric<T> {
	private T num;

	public NumGeneric() {
		
	}

	public NumGeneric(T num) {
		this.setNum(num);
	}

	public T getNum() {
		return num;
	}

	public void setNum(T num) {
		this.num = num;
	}
	
	// Test 
	public static void main(String[] args) {
		NumGeneric<Integer> intNum = new NumGeneric<>();
		intNum.setNum(10);
		System.out.println("Integer:" + intNum.getNum());
		
		NumGeneric<Float> floatNum = new NumGeneric<>();
		floatNum.setNum(5.0f);
		System.out.println("Float:" + floatNum.getNum());
	}
}

The definition and use of generic classes can be passed into objects of different classes as parameters

4. Customize generic methods


public <T extends Number> void printValue(T t) {
	System.out.println(t);
}

Note:

Generic methods are not fixed in generic classes < T > Must be written between the modifier and the return value type.

5. Generic Summary

1. Why use generics

Forced type conversion is not needed to avoid security risks of runtime exceptions

2. The type declared by the variable must match the type passed to the actual object.

3. Generics as method parameters


public void sellGoods(List<? extends Goods> goods)

It can be a subclass of Goods and Goods as a parameter type of generic type, and extends can be followed by the name of interface as well as the name of class.

4. public void sellGoods (List) < ? super Goods > goods)

The representation can be the parameter type of Goods class and its superclass as generic

5. Customize generic classes

6. Customize generic methods


Related articles: