背景
在没有泛型前,一旦把一个对象丢进集合中,集合就会忘记对象的类型,把所有的对象都当成 Object 类型处理。当程序从集合中取出对象后,就需要进行强制类型转换,这种转换很容易引起 ClassCastException 异常。
定义
程序在创建集合时指定集合元素的类型。增加了泛型支持后的集合,可以记住集合中元素的类型,并可以在编译时检查集合中元素的类型,如果试图向集合中添加不满足类型要求的对象,编译器就会报错。
示例
两个示例,简单介绍泛型的基本使用。
集合使用泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
public class DiamondTest { public static void main(String[] args) { List<String> books = new ArrayList<>(); books.add("learn"); books.add("java"); books.forEach(book -> System.out.println(book.length()));
Map<String, List<String>> schoolsInfo = new HashMap<>(); List<String> schools = new ArrayList<>(); schools.add("i"); schools.add("love"); schoolsInfo.put("java", schools); schoolsInfo.forEach((key, value) -> System.out.println(key + "--->" + value)); } }
|
类、接口使用泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class Apple<T> { private T info; public Apple() {} public Apple(T info) { this.info = info; } public void setInfo(T info) { this.info = info; } public T getinfo() { return this.info; } public static void main(String[] args) { Apple<String> a1 = new Apple<>("Apple"); System.out.println(a1.getinfo()); Apple<Double> a2 = new Apple<>(5.67); System.out.println(a2.getinfo()); } }
|