Generic learning

When you create a collection of types of elements in a set limit

int [] arr = new int [10]; int type array can store data

Date [] att = new Date [10] array can only store the data type Date

Collection col = new ArrayList();

col.add("hello")

col.add(123)

All the elements are added to the collection object type, ClassCastException exception if there will be a downward transition

Symbols used are generic <T>

Generics only during compilation work, (bypassing the compiler, the generics will not work)

package com.wyq.StringBuffer;

import java.util.ArrayList;
import java.util.Collection;

public class TestGend {
	public static void main(String[] args) {
		Collection<Integer> col = new ArrayList<Integer>();
		/**
		 * 这里泛型定义了集合中存储的类型为Integer类型
		 * 如果往集合中存储其他类型的数据,会出现报错,报错原因是数据类型与集合定义的类型不匹配
		 */
		col.add("hello");
		col.add(123);
		col.add("world");
		System.out.println(col);
		for (Object o : col) {
			System.out.println(o);
		}

	}

}

 

Guess you like

Origin blog.csdn.net/wyqwilliam/article/details/93323648