泛型的作用
-
泛型:类似于标签标签
-
集合容器类在设计阶段/声明阶段不能确定这个容器是用来装什么类型的对象,所以在jdk1.5之前只能把元素类型设计为Object,在jdk1.5之后使用泛型来解决
-
故把元素的类型设计成一个参数,叫泛型,如:Cllection、List,其中的就是类型参数,即泛型
-
所谓泛型,就是允许在定义类、接口时通过一个标识标识类中某个属性的类型或者是某个方法的返回值及参数类型;这个类型参数将在使用时确定
-
泛型的作用
- 在集合中未使用泛型时:
package www.bh.c.genetest; import java.util.ArrayList; public class Test1 { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add(85); list.add(86); list.add(89); list.add(90); //缺点一:类型不安全 list.add("考试"); //问题二:强转时,可能会出现ClassCastException for (Object score:list){ int stuScore=(Integer) score; System.out.println(stuScore); } } }
- 在集合中使用泛型时:
package www.bh.c.genetest; import java.util.ArrayList; public class Test1 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(85); list.add(86); list.add(89); list.add(90); //编译时,就会进行类型检查,保证数据的安全 //list.add("考试"); //避免了强转操作,避免报错ClassCastException for (Integer score:list){ int stuScore= score; System.out.print(stuScore+" ");//85 86 89 90 } Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" ");//85 86 89 90 } } }
集合中使用泛型
//HashMap为例
package www.bh.c.genetest;
import java.util.*;
public class Test1 {
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<>();
map.put("A",12);
map.put("B",13);
map.put("C",15);
//泛型的嵌套
Set<Map.Entry<String, Integer>> entry = map.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = entry.iterator();
while (iterator.hasNext()){
Map.Entry<String, Integer> next = iterator.next();
String key = next.getKey();
Integer value = next.getValue();
System.out.println(key+"---->"+value);//A---->12
//B---->13
//C---->15
}
}
}
- 泛型使用总结:
- jdk 5.0新增的特性
- 集合接口或集合类在jdk5.0时都修改为带泛型的结构
- 在实例化集合时,可以指明具体的泛型类型
- 指明完以后,在集合类或接口中凡是定义类或接口时,部内结构(比如:方法、构造器、属性等)使用到类的泛型的位置,都指定为实例化的泛型类型,比如:add(E e) —>实例化以后:add(Integer e)
- 泛型的类型必须是类,不能是基本数据类型,需要用到基本数据类型的位置,拿包装类
- 如果实例化时,没有指明泛型的类型,默认类型为java.Lang.Object类型