栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java】泛型经典使用案列

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java】泛型经典使用案列

泛型经典使用案列

泛型,又称参数化类型,是JDK5.0出现的新特性,解决数据类型的安全性问题。泛型可以保证若程序在编译时没有发出警告,运行时就不会发生ClassCastException,同时,代码更加简洁、健壮。泛型的作用是可以在类声明时通过一个标识表示类中某个属性的类型、某个方法的返回值的类型、参数类型。

1、问题描述

(1) 定义Employee类:
① 该类包含: private成员变量name,sal,birthday, 其中birthday为MyDate类的对象;
② 为每一个属性定义getter, setter方法;
③ 重写toString方法输出name, sal, birthday
④ MyDate类包含: private成员变量month,day,year; 并为每一个属性定义getter和setter方法;
⑤ 创建该类的3个对象,并把这些对象放入ArrayList集合中(ArrayList 需使用泛型来定义),
(2) 对集合中的元素进行排序,并遍历输出:
① 排序方式:调用ArrayList 的sort方法,传入Comparator对象[使用泛型],先按照name排序,如果name相同,则按生日日期的先后排序。

2、代码编写

(1) 因为Employee类的属性birthday为MyDate类的对象,所以首先要创建MyDate类。

class Mydate{
    
    private int year;
    private int month;
    private int day;

    
    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 year+"-"+month+"-"+day;
    }
}

(2)创建Employee类

class Employee{
    
    private String name;
    private double salary;
    private Mydate birthday;

    
    public Employee(String name, double salary, Mydate birthday){
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Mydate getBirthday() {
        return birthday;
    }
    public void setBirthday(Mydate birthday) {
        this.birthday = birthday;
    }

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

(3)编写主程序,构造带Employee对象泛型的ArrayList对象

        
        ArrayList arrayList = new ArrayList();

(4)给arrayList添加元素

        
        arrayList.add(new Employee("DMS",2000,new Mydate(1997,12,14)));
        arrayList.add(new Employee("LHX",2000,new Mydate(1997,12,13)));
        arrayList.add(new Employee("DMS",2000,new Mydate(1997,12,12)));

(5)输出排序前arrarList

        
        System.out.println("======排序前======");
        System.out.println(arrayList);

(6)调用ArrayList的sort( )方法,传入泛型为Employee对象的自定义的匿名内部类Comparator

          
          arrayList.sort(new Comparator() {
            @Override
            public int compare(Employee o1, Employee o2) {
              }
           });

(6)重写实现的compare( )方法:先按照name排序,如果name相同,则按生日日期的先后排序。

① 先对传入的参数进行验证

        / *①对输入的参数进行验证*/
         if(!(o1 instanceof Employee && o2 instanceof Employee))
           {
              System.out.println("传入参数类型不正确!!!");
               return 0;
           }

②-1、比较name

         
         int nameCompare = o1.getName().compareTo(o2.getName());

②-1.1如果name不相等,就返回比较值

         //②-1.1如果name不相等,就返回比较值
          if(nameCompare != 0){
                 return nameCompare;
          }

②-1.2如果name相等,就比较birthday

         //②-1.2如果name相等,就比较birthday
          else{
             //比较year
             int yearCompare = o1.getBirthday().getYear()-o2.getBirthday().getYear();

②-1.2.1如果year不相等,就返回比较值

        //②-1.2.1如果year不相等,就返回比较值
           if(yearCompare != 0){
                return yearCompare;
             }

②-1.2.2如果year相等,就比较month

       else{
             //②-1.2.2如果year相等,就比较month
             int monthCompare = o1.getBirthday().getMonth()-o2.getBirthday().getMonth();

②-1.2.2.1如果month不相等,就返回比较值

         //②-1.2.2.1如果month不相等,就返回比较值
            if(monthCompare != 0){
                  return monthCompare;
              }

②-1.2.2.2如果month相等,就比较day

           //②-1.2.2.2如果month相等,就比较day
            int dayCompare = o1.getBirthday().getDay()-o2.getBirthday().getDay();
            return dayCompare;
             }
          }
3、代码运行结果

4、完整代码
import java.util.ArrayList;
import java.util.Comparator;


public class Generic01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        
        ArrayList arrayList = new ArrayList();
        
        arrayList.add(new Employee("DMS",2000,new Mydate(1997,12,14)));
        arrayList.add(new Employee("LHX",2000,new Mydate(1997,12,13)));
        arrayList.add(new Employee("DMS",2000,new Mydate(1997,12,12)));
        
        System.out.println("======排序前======");
        System.out.println(arrayList);
        
        arrayList.sort(new Comparator() {
        
            @Override
            public int compare(Employee o1, Employee o2) {
                
                if(!(o1 instanceof Employee && o2 instanceof Employee))
                {
                    System.out.println("传入参数类型不正确!!!");
                    return 0;
                }
                
                int nameCompare = o1.getName().compareTo(o2.getName());
                //②-1.1如果name不相等,就返回比较值
                if(nameCompare != 0){
                   return nameCompare;
                }
                //②-1.2如果name相等,就比较birthday
                else{
                    //比较year
                    int yearCompare = o1.getBirthday().getYear()-o2.getBirthday().getYear();
                    //②-1.2.1如果year不相等,就返回比较值
                    if(yearCompare != 0){
                        return yearCompare;
                    }
                    else{
                        //②-1.2.2如果year相等,就比较month
                        int monthCompare = o1.getBirthday().getMonth()-o2.getBirthday().getMonth();
                        //②-1.2.2.1如果month不相等,就返回比较值
                        if(monthCompare != 0){
                            return monthCompare;
                        }
                        //②-1.2.2.2如果month相等,就比较day
                        int dayCompare = o1.getBirthday().getDay()-o2.getBirthday().getDay();
                        return dayCompare;
                    }
                }
            }
        });
        
        System.out.println("======排序后======");
        System.out.println(arrayList);
    }
}

class Employee{
    
    private String name;
    private double salary;
    private Mydate birthday;

    
    public Employee(String name, double salary, Mydate birthday){
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Mydate getBirthday() {
        return birthday;
    }
    public void setBirthday(Mydate birthday) {
        this.birthday = birthday;
    }

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

class Mydate{
    
    private int year;
    private int month;
    private int day;

    
    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 year+"-"+month+"-"+day;
    }
}
5、代码优化

对birthday的比较应该交给MyDate类去比较,封装在Mydate类,将来可维护性和复用性就大大增强。
(1)给Mydate类实现Comparable接口,指定为泛型Mydate比较

      class Mydate implements Comparable{
      }

(2)实现方法compareTo( ),用于year-month-day的比较

   @Override
    public int compareTo(Mydate o){
        //比较year
        int yearCompare = this.year-o.getYear();
        //②-1.2.1如果year不相等,就返回比较值
        if(yearCompare != 0){
            return yearCompare;
        }
        else{
            //②-1.2.2如果year相等,就比较month
            int monthCompare = this.month-o.getMonth();
            //②-1.2.2.1如果month不相等,就返回比较值
            if(monthCompare != 0){
                return monthCompare;
            }
            //②-1.2.2.2如果month相等,就比较day
            int dayCompare = this.day-o.getDay();
            return dayCompare;
        }
    }

(3)比较birthday时,调用Mydate类(o1.getBirthday( ))的compareTo方法

    //②-1.2如果name相等,就比较birthday
     else{
          return o1.getBirthday().compareTo(o2.getBirthday());
         }

完整代码

import java.util.ArrayList;
import java.util.Comparator;


public class Generic02 {
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        
        ArrayList arrayList = new ArrayList();
        
        arrayList.add(new Employee("DMS",2000,new Mydate(1997,12,14)));
        arrayList.add(new Employee("LHX",2000,new Mydate(1997,12,13)));
        arrayList.add(new Employee("DMS",2000,new Mydate(1997,12,12)));
        
        System.out.println("======排序前======");
        System.out.println(arrayList);
        
        arrayList.sort(new Comparator() {
        
            @Override
            public int compare(Employee o1, Employee o2) {
                
                if(!(o1 instanceof Employee && o2 instanceof Employee))
                {
                    System.out.println("传入参数类型不正确!!!");
                    return 0;
                }
                
                int nameCompare = o1.getName().compareTo(o2.getName());
                //②-1.1如果name不相等,就返回比较值
                if(nameCompare != 0){
                   return nameCompare;
                }
                //②-1.2如果name相等,就比较birthday
                else{
                  return o1.getBirthday().compareTo(o2.getBirthday());
                }
            }
        });
        
        System.out.println("======排序后======");
        System.out.println(arrayList);
    }
}


class Employee{
    
    private String name;
    private double salary;
    private Mydate birthday;

    
    public Employee(String name, double salary, Mydate birthday){
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Mydate getBirthday() {
        return birthday;
    }
    public void setBirthday(Mydate birthday) {
        this.birthday = birthday;
    }

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


 class Mydate implements Comparable{

    
    private int year;
    private int month;
    private int day;

    
    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 year+"-"+month+"-"+day;
    }
    @Override
    public int compareTo(Mydate o){
        //比较year
        int yearCompare = this.year-o.getYear();
        //②-1.2.1如果year不相等,就返回比较值
        if(yearCompare != 0){
            return yearCompare;
        }
        else{
            //②-1.2.2如果year相等,就比较month
            int monthCompare = this.month-o.getMonth();
            //②-1.2.2.1如果month不相等,就返回比较值
            if(monthCompare != 0){
                return monthCompare;
            }
            //②-1.2.2.2如果month相等,就比较day
            int dayCompare = this.day-o.getDay();
            return dayCompare;
        }
    }
}

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/785852.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号