JAVA Foundation (19) - Generics

Generics

Before jdk1.4, any type of object in the container can be stored, but when it is retrieved. When you need to use the specific content of the object, you need to downcast. However, the type of the object is inconsistent, which will cause a ClassCastException to occur in the downcast. In order to avoid this problem, it can only be controlled subjectively, and the type of objects stored in the collection should be consistent.

After jdk1.5, this problem has been solved. When defining a collection, the specific type of the elements stored in the collection is directly clarified. In this way, the compiler can check the types of objects stored in the collection at compile time. Compilation fails as soon as a type mismatch is found. This is generic technology.

benefit:

  • Shifting run-time problems to compile-time can better allow programmers to identify and solve problems.
  • Avoid the trouble of downcasting.

Summary: Generics are a security mechanism applied at compile time.

package demo;
import java.util.*;
public class Demo {

	public static void main(String[] args) {	
		
	   List<Person> list=new ArrayList<Person>();
	   list.add(new Person("小红",20));
	   list.add(new Person("小明",20));
	   list.add(new Person("小虾",20));
	   
	   for(Iterator<Person> it=list.iterator();it.hasNext();) {
            //使用泛型,这里就不需要像之前那样转型。
		    it.next().get();
	   }
	}
			
}
  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325229453&siteId=291194637