First look at generics

Question 1:
What is generic?
Answer:
Baidu has a standard explanation on the Internet.

Java generics is a new feature introduced in JDK 5.
Generics provides a compile-time type safety detection mechanism, which allows programmers to detect illegal types at compile time.
The essence of generics is the parameterized type, which means that the data type being operated on is specified as a parameter.

I combined with the words in the Head first java book to refer to and understand each other.

Generics provide a way to check type safety. That is to avoid the unreasonable situation of putting cats into mouse collections. And most of the programs we encounter with generics are related to processing collections.

Three things to know about generics:

  • Create an instance of a generic class
    must specify what it allows
new ArrayList<Song>();//Song必须指定
  • Declare and specify variables of generic type
List<Song> songList = new ArrayList<Song>();
  • Call a method of a generic type
 void foo(List<Song> list)
 x.foo(songList);

Question 2:
How to use generics?

  1. Use generic classes
public class Arraylist<E> extends AbstractList<E> implements List<E>{
	public boolean add(E o){  //E代表集合的元素类型
	//更多代码
	}
}
  1. Use the type parameters defined in the class declaration
public class ArrayList<E> extends AbtractList<E>...{
	public boolean add(E o)//只能使用E
}
  1. Use type parameters not defined in the class declaration
 public <T extends Animal> void takeThing(ArrayList<T> list)
 //<T extends Animal> 是方法声明的一部分,表示动物或者动物的子类的ArrayList是合法的

Note: From a generic point of view, extends stands for extends or implement

Published 27 original articles · praised 2 · visits 680

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/104488399