0
点赞
收藏
分享

微信扫一扫

Java泛型笔记

海滨公园 2022-02-01 阅读 62

12-1 泛型(Generic)概述

4.在集合中有泛型时,只有指定类型才可以添加到集合中(类型安全)。 读取出来的对象不需要强转(便捷)。

5.总结:Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生ClassCastException异常。同时,代码更加简洁、健壮。

12-2 在集合中使用泛型

import org.junit.Test;
import java.util.*;
/*
 * 泛型的使用
 * 1.jdk 5.0新增的特性
 *
 * 2.在集合中使用泛型:
 *  总结:
 *  ① 集合接口或集合类在jdk5.0时都修改为带泛型的结构。
 *  ② 在实例化集合类时,可以指明具体的泛型类型
 *  ③ 指明完以后,在集合类或接口中凡是定义类或接口时,内部结构(比如:方法、构造器、属性等)使用到类的泛型的位置,都指定为实例化的泛型类型。
 *    比如:add(E e)  --->实例化以后:add(Integer e)
 *  ④ 注意点:泛型的类型必须是类,不能是基本数据类型。需要用到基本数据类型的位置,拿包装类替换
 *  ⑤ 如果实例化时,没有指明泛型的类型。默认类型为java.lang.Object类型。
 *
 * 3.如何自定义泛型结构:泛型类、泛型接口;泛型方法。见 GenericTest1.java
 */
public class GenericTest {
    //在集合中使用泛型之前的情况:
    @Test
    public void test1(){
        ArrayList list = new ArrayList();
        //需求:存放学生的成绩
        list.add(78);
        list.add(76);
        list.add(89);
        list.add(88);
        //问题一:类型不安全
//        list.add("Tom");
        for(Object score : list){
            //问题二:强转时,可能出现ClassCastException
            int stuScore = (Integer) score;
            System.out.println(stuScore);
        }
    }
    //在集合中使用泛型的情况:以ArrayList为例
    @Test
    public void test2(){
       ArrayList<Integer> list =  new ArrayList<Integer>();

        list.add(78);
        list.add(87);
        list.add(99);
        list.add(65);
        //编译时,就会进行类型检查,保证数据的安全
//        list.add("Tom");
        //方式一:
//        for(Integer score : list){
//            //避免了强转操作
//            int stuScore = score;
//            System.out.println(stuScore);
//        }
        //方式二:
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            int stuScore = iterator.next();
            System.out.println(stuScore);
        }
    }
    //在集合中使用泛型的情况:以HashMap为例
    @Test
    public void test3(){
//     方式一:   Map<String,Integer> map = new HashMap<String,Integer>();
//方式二:jdk7新特性:类型推断
        Map<String,Integer> map = new HashMap<>();

        map.put("Tom",87);
        map.put("Jerry",87);
        map.put("Jack",67);

//        map.put(123,"ABC");
        //泛型的嵌套
        Set<Map.Entry<String,Integer>> entry = map.entrySet();
        Iterator<Map.Entry<String, Integer>> iterator = entry.iterator();
         //取map内容
        while(iterator.hasNext()){
            Map.Entry<String, Integer> e = iterator.next();
            String key = e.getKey();
            Integer value = e.getValue();
            System.out.println(key + "----" + value);
        }
    }
}

12-3 自定义泛型结构

自定义泛型类
自定义泛型接口
自定义泛型方法

举报

相关推荐

0 条评论