泛型的使用

泛型

package com.sq.sgg;

import org.junit.Test;

import java.util.*;

/*
    泛型的使用
    1.jdk 5.0 新增的特性
    2.在集合中使用泛型:
        总结:
            ① 集合接口或集合类在 jdk5.0 时都修改为带泛型的结构。
            ② 在实例化集合类时,可以指明具体的泛型类型
            ③ 指明完以后,在集合类或接口中凡是定义类或接口时,内部结构(比如:方法、构造器、属性等)使用到类的泛型的位置,都指定为实例化的泛型类型
                 比如:add(E e) ---> 实例化以后:add(Integer e)
            ④ 注意点:泛型的类型必须时类,不能是基本数据类型。需要用到基本数据类型的位置,拿包装类替换
            ⑤ 如果实例化时,没有指明泛型的类型。默认类型为 java.lang.Object 类型

 */
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);
        }
//        78
//        76
//        89
//        88
    }

    // 在集合中使用泛型的情况:以 ArrayList 为例
    @Test
    public void test2(){
        ArrayList<Integer> list = new ArrayList<>();// <>内不能放基本数据类型,只能放包装类型
        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();

        while(iterator.hasNext()){
            Map.Entry<String,Integer> e = iterator.next();
            String key = e.getKey();
            Integer value = e.getValue();
            System.out.println(key + "---" + value);
        }
//        Tom---87
//        Jerry---87
//        Jack---67


    }
}

改为泛型的程序:

package com.sq.exer;

/*
    MyDate 类包含:
    private 成员变量 year,month,day;并未每一个属性定义:getter,setter 方法;

 */
public class MyDate implements Comparable<MyDate>{
    private int year;
    private int month;
    private int day;

    public MyDate() {
    }

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }

//    @Override
//    public int compareTo(Object o) {
//        if(o instanceof MyDate){
//            MyDate m = (MyDate) o;
//            // 比较年
//            int minusYear = this.getYear() - m.getYear();
//            if(minusYear != 0){
//                return minusYear;
//            }
//            // 比较月
//            int minusMonth = this.getMonth() - m.getMonth();
//            if(minusMonth != 0){
//                return minusMonth;
//            }
//            // 比较日
//            return this.getDay() - m.getDay();
//        }
//        throw new RuntimeException("传入的数据类型不一致!");
//    }

    @Override
    public int compareTo(MyDate o) {
        // 比较年
        int minusYear = this.getYear() - o.getYear();
        if(minusYear != 0){
            return minusYear;
        }
        // 比较月
        int minusMonth = this.getMonth() - o.getMonth();
        if(minusMonth != 0){
            return minusMonth;
        }
        // 比较日
        return this.getDay() - o.getDay();
    }
}

package com.sq.exer;

/*
    定义一个 Employee 类
    该类包含:private 成员变量 name,age,birthday,其中 birthday 为MyDate 类的对象;
    并为每一个属性定义:getter,setter 方法:
    并重写 toString 方法输出 name,age,birthday
 */
public class Employee implements Comparable<Employee>{
    private String name;
    private int age;
    private MyDate birthday;

    public Employee() {
    }

    public Employee(String name, int age, MyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    // 指明泛型时的写法
    @Override
    public int compareTo(Employee o) {
        return this.name.compareTo(o.name);
    }

    // 没有指明泛型时的写法
    // 按 name 排序
//    @Override
//    public int compareTo(Object o) {
//        if(o instanceof Employee){
//            Employee e = (Employee) o;
//            return this.name.compareTo(e.name);
//        }
        return 0;
//        throw new RuntimeException("传入的数据类型不一致!");
//    }
}

package com.sq.exer;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/*
    创建该类的 5 个对象,并把这些对象放入 TreeSet 集合中(下一章:TreeSet 需使用泛型来定义)
    分别按以下两种方式对集合中的元素进行排序,并遍历输出:

    1)使 Employee 实现 Comparable 接口,并按 name 排序
    2)创建 TreeSet 时传入 Comparator 对象,按生日日期的先后顺序。
 */
public class EmployeeTest {

    // 问题一:使用自然排序
    @Test
    public void test1(){
        TreeSet<Employee> set = new TreeSet<Employee>();

        Employee e1 = new Employee("liudehua",55,new MyDate(1965,5,4));
        Employee e2 = new Employee("zhangxueyou",43,new MyDate(1987,5,4));
        Employee e3 = new Employee("guofucheng",55,new MyDate(1987,5,9));
        Employee e4 = new Employee("liming",55,new MyDate(1954,8,12));
        Employee e5 = new Employee("liangchaowei",55,new MyDate(1978,12,4));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator<Employee> iterator = set.iterator();
        while(iterator.hasNext()){
            Employee employee = iterator.next();
            System.out.println(employee);
        }
//        Employee{name='guofucheng', age=55, birthday=MyDate{year=1987, month=5, day=9}}
//        Employee{name='liangchaowei', age=55, birthday=MyDate{year=1978, month=12, day=4}}
//        Employee{name='liming', age=55, birthday=MyDate{year=1954, month=8, day=12}}
//        Employee{name='liudehua', age=55, birthday=MyDate{year=1965, month=5, day=4}}
//        Employee{name='zhangxueyou', age=43, birthday=MyDate{year=1987, month=5, day=4}}
    }

    // 按生日日期的先后排序
    @Test
    public void test2(){

        TreeSet<Employee> set = new TreeSet<>(new Comparator<Employee>() {
            // 使用泛型以后的写法
            @Override
            public int compare(Employee o1, Employee o2) {
                MyDate b1 = o1.getBirthday();
                MyDate b2 = o2.getBirthday();
//                    // 方式一:
                    // 比较年
                    int minusYear = b1.getYear() - b2.getYear();
                    if(minusYear != 0){
                        return minusYear;
                    }
                    // 比较月
                    int minusMonth = b1.getMonth() - b2.getMonth();
                    if(minusMonth != 0){
                        return minusMonth;
                    }
                    // 比较日
                    return b1.getDay() - b2.getDay();
//
//                    // 方式二:MyDate 类实现 Comparable 并重写 compareTo
                    return b1.compareTo(b2);
            }
            // 使用泛型之前的写法
//            @Override
//            public int compare(Object o1, Object o2) {
//                if(o1 instanceof Employee && o2 instanceof Employee){
//                    Employee e1 = (Employee) o1;
//                    Employee e2 = (Employee) o2;
//
//                    MyDate b1 = e1.getBirthday();
//                    // 效果一样
//                    MyDate b2 = e2.getBirthday();
//                    // 方式一:
                    // 比较年
                    int minusYear = b1.getYear() - b2.getYear();
                    if(minusYear != 0){
                        return minusYear;
                    }
                    // 比较月
                    int minusMonth = b1.getMonth() - b2.getMonth();
                    if(minusMonth != 0){
                        return minusMonth;
                    }
                    // 比较日
                    return b1.getDay() - b2.getDay();
//
//                    // 方式二:MyDate 类实现 Comparable 并重写 compareTo
//                    return b1.compareTo(b2);
//                }
                return 0;
//                throw new RuntimeException("传入的数据类型不一致!");
//            }
        });

        Employee e1 = new Employee("liudehua",55,new MyDate(1965,5,4));
        Employee e2 = new Employee("zhangxueyou",43,new MyDate(1987,5,4));
        Employee e3 = new Employee("guofucheng",55,new MyDate(1987,5,9));// 若 日:9 为 日:4 则此条记录不显示,因为相等
        Employee e4 = new Employee("liming",55,new MyDate(1954,8,12));
        Employee e5 = new Employee("liangchaowei",55,new MyDate(1978,12,4));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator<Employee> iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
//        Employee{name='liming', age=55, birthday=MyDate{year=1954, month=8, day=12}}
//        Employee{name='liudehua', age=55, birthday=MyDate{year=1965, month=5, day=4}}
//        Employee{name='liangchaowei', age=55, birthday=MyDate{year=1978, month=12, day=4}}
//        Employee{name='zhangxueyou', age=43, birthday=MyDate{year=1987, month=5, day=4}}
//        Employee{name='guofucheng', age=55, birthday=MyDate{year=1987, month=5, day=9}}
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
泛型(Generics)是一种在编程语言中实现参数化类型的技术,可以让我们编写更加灵活和通用的代码。下面是一个泛型使用案例: 假设我们有一个需求,需要实现一个通用的栈(Stack)数据结构,可以存储任何类型的元素。我们可以使用泛型来实现这个通用的栈数据结构。以下是一个基于Java的示例代码: ```java public class Stack<T> { private ArrayList<T> items; public Stack() { items = new ArrayList<T>(); } public void push(T item) { items.add(item); } public T pop() { if (items.isEmpty()) { throw new RuntimeException("Stack is empty"); } return items.remove(items.size() - 1); } public boolean isEmpty() { return items.isEmpty(); } } ``` 在上面的代码中,我们使用了一个类型参数 `T`,它代表任何类型。我们在类的定义中使用了 `<T>` 来声明这个类是一个泛型类,它可以接受任何类型的元素。在类的内部,我们使用 `T` 来代表元素的类型。我们将元素存储在一个 `ArrayList<T>` 中,这个 `ArrayList` 可以存储任何类型的元素。 我们定义了三个方法:`push()`、`pop()` 和 `isEmpty()`。`push()` 方法用于将元素压入栈中,`pop()` 方法用于弹出栈顶元素,并从栈中移除它,`isEmpty()` 方法用于判断栈是否为空。 使用泛型,我们可以使用这个通用的栈数据结构来存储任何类型的元素,例如: ```java Stack<Integer> intStack = new Stack<Integer>(); intStack.push(1); intStack.push(2); intStack.push(3); intStack.pop(); // 返回 3 intStack.pop(); // 返回 2 Stack<String> strStack = new Stack<String>(); strStack.push("Hello"); strStack.push("World"); strStack.pop(); // 返回 "World" ``` 在上面的示例代码中,我们分别使用了 `Stack<Integer>` 和 `Stack<String>` 来存储整数和字符串类型的元素。由于使用泛型,这个通用的栈数据结构可以存储任何类型的元素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值