Java 泛型举例

  1 package com.bytezero.genericity;
  2 
  3 import org.junit.Test;
  4 
  5 import java.util.*;
  6 
  7 /**
  8  * @author Bytezero1·zhenglei!    Email:420498246@qq.com
  9  * create  2021-11-22 11:47
 10  *   泛型的使用
 11  *   1.jdk5.0新特性
 12  *
 13  *   2.在集合中使用泛型:
 14  *   总结:
 15  *   1.集合接口或集合类在jdk5.0时都修改为带泛型的结构
 16  *   2.在实例化集合类时,可以指明具体的泛型类型
 17  *   3.指明完以后,在集合类或接口中凡是定义类或接口时,内部结构(比如:方法 构造器 属性等..)使用到类的泛型位置,
 18  *   都指定为实例化的泛型类型  比如 :add(E e) -->实例化以后:add(Integer e)
 19  *   4.注意点:泛型的类型必须是类,不能是基本数据类型,需要用到基本数据类型的位置,拿包装类来替换
 20  *   5.如果实例化时,没有指明泛型的类型,默认类型为 java.lang.Object类型
 21  */
 22 public class genericityTest {
 23 
 24     //在集合中使用泛型之前的情况
 25     @Test
 26     public  void test1(){
 27         ArrayList list = new ArrayList();
 28 
 29         //需求:存放学生的成绩
 30         list.add(18);
 31         list.add(28);
 32         list.add(38);
 33         list.add(48);
 34         list.add(58);
 35 
 36         //问题一:类型不安全
 37 //        list.add("Tom");    //类型错误
 38 
 39         for(Object score : list){
 40 
 41             //问题二   强转时 ,可能出现ClassCastException
 42             int stuScore =  (Integer) score;
 43 
 44             System.out.println(stuScore);
 45 
 46         }
 47 
 48 
 49 
 50 
 51     }
 52 
 53 
 54     //在集合中使用泛型的情况
 55     @Test
 56     public  void test02(){
 57         ArrayList<Integer> list  = new ArrayList<Integer>();
 58 
 59         list.add(18);
 60         list.add(18);
 61         list.add(18);
 62         list.add(18);
 63         list.add(18);
 64         list.add(18);
 65 
 66         //编译时 就会进行类型数据检查  保证数据的安全
 67 //        list.add("Tom");
 68 
 69         //方式一:
 70 //        for(Integer score : list){
 71 //            //避免了强转的操作
 72 //            int stuScore = score;
 73 //
 74 //            System.out.println(stuScore);
 75 
 76         //方式二
 77         Iterator<Integer> iterator = list.iterator();
 78         while (iterator.hasNext()){
 79             int stuScore = iterator.next();
 80             System.out.println(stuScore);
 81     }
 82     }
 83     //在集合中使用泛型的情况,以HashMap为例
 84     @Test
 85     public void test3(){
 86         Map<String,Integer> map = new HashMap<String, Integer>() ;
 87 
 88         map.put("Tom",89);
 89         map.put("jer",59);
 90         map.put("jon",29);
 91         map.put("andi",99);
 92 
 93 //        map.put(123,"asf");
 94         //泛型嵌套
 95        Set<Map.Entry<String,Integer>>entry = map.entrySet();
 96        Iterator<Map.Entry<String,Integer>> iterator = entry.iterator();
 97 
 98        while (iterator.hasNext()){
 99            Map.Entry<String, Integer> entry1 = iterator.next();
100            String key = entry1.getKey();
101            Integer value = entry1.getValue();
102            System.out.println(key + "-----" + value);
103        }
104 
105     }
106 
107 
108 
109 
110 }

 

posted on 2021-11-22 12:50  Bytezero!  阅读(372)  评论(0编辑  收藏  举报