在创建集合的时候,对集合中的元素的类型进行限制
int [] arr = new int [10];数组中只能存储int类型的数据
Date [] att = new Date [10] 数组中只能存储Date类型的数据
Collection col = new ArrayList();
col.add("hello")
col.add(123)
向集合中添加的所有元素均为object类型,在向下转型的时候就会出现ClassCastException异常
泛型所使用的符号是<T>
泛型只在编译期间起作用,(绕过编译,泛型就不起作用了)
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);
}
}
}