【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类。

/*(1) 因为Employee类的属性birthday为MyDate类的对象,所以首先要创建MyDate类。*/
class Mydate{
    /*MyDate类的三个属性*/
    private int year;
    private int month;
    private int day;

    /*MyDate类构造器*/
    public Mydate(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    /*MyDate类所有属性的get和set方法*/
    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;
    }

    /*重写MyDate类的toString()方法*/
    @Override
    public String toString(){
        return year+"-"+month+"-"+day;
    }
}

(2)创建Employee类

/*(2)创建Employee类*/
class Employee{
    /*Employee类的三个属性*/
    private String name;
    private double salary;
    private Mydate birthday;

    /*Employee类的构造器*/
    public Employee(String name, double salary, Mydate birthday){
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    /*Employee类所有属性的get和set方法*/
    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;
    }

    /*重写Employee类的toString()方法*/
    @Override
    public String toString() {
        return "\n"+"Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }
}

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

        /*(3)编写主程序,构造带Employee对象泛型的ArrayList对象*/
        ArrayList arrayList = new ArrayList();

(4)给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

        /*(5)输出排序前arrarList*/
        System.out.println("======排序前======");
        System.out.println(arrayList);

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

          /*(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

         /*②-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、代码运行结果

【Java】泛型经典使用案列_第1张图片

4、完整代码

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

/*定义Employee类
1)该类包含: private成员变量name,sal,birthday, 其中birthday为MyDate类的对
象;
2)为每一个属性定义getter, setter方法;
3)重写toString方法输出name, sal, birthday
●4) MyDate类包含: private成员变量month,day,year; 并为每一个属性定义getter,●
setter方法;
5)创建该类的3个对象,并把这些对象放入ArrayList集合中(ArrayList 需使用泛
型来定义),
对集合中的元素进行排序,并遍历输出:
排序方式:调用ArrayList 的sort方法,传入Comparator对象[使用泛型],先按照
name排序,如果name相同,则按生日日期的先后排序。[即: 定制排序)
有一定难度,比较经典泛型使用案例
*/
public class Generic01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        /*(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() {
        /*(7)重写实现的compare( )方法:先按照name排序,如果name相同,则按生日日期的先后排序。*/
            @Override
            public int compare(Employee o1, Employee o2) {
                /*①对输入的参数进行验证*/
                if(!(o1 instanceof Employee && o2 instanceof Employee))
                {
                    System.out.println("传入参数类型不正确!!!");
                    return 0;
                }
                /*②-1、比较name*/
                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;
                    }
                }
            }
        });
        /*(8)输出排序前arrarList*/
        System.out.println("======排序后======");
        System.out.println(arrayList);
    }
}
/*(2)创建Employee类*/
class Employee{
    /*Employee类的三个属性*/
    private String name;
    private double salary;
    private Mydate birthday;

    /*Employee类的构造器*/
    public Employee(String name, double salary, Mydate birthday){
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    /*Employee类所有属性的get和set方法*/
    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;
    }

    /*重写Employee类的toString()方法*/
    @Override
    public String toString() {
        return "\n"+"Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }
}
/*(1) 因为Employee类的属性birthday为MyDate类的对象,所以首先要创建MyDate类。*/
class Mydate{
    /*Mydate类的三个属性*/
    private int year;
    private int month;
    private int day;

    /*Mydate类构造器*/
    public Mydate(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    /*Mydate类所有属性的get和set方法*/
    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;
    }

    /*重写Mydate类的toString()方法*/
    @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;

/*定义Employee类
1)该类包含: private成员变量name,sal,birthday, 其中birthday为MyDate类的对
象;
2)为每一个属性定义getter, setter方法;
3)重写toString方法输出name, sal, birthday
●4) MyDate类包含: private成员变量month,day,year; 并为每一个属性定义getter,●
setter方法;
5)创建该类的3个对象,并把这些对象放入ArrayList集合中(ArrayList 需使用泛
型来定义),
对集合中的元素进行排序,并遍历输出:
排序方式:调用ArrayList 的sort方法,传入Comparator对象[使用泛型],先按照
name排序,如果name相同,则按生日日期的先后排序。[即: 定制排序)
有一定难度,比较经典泛型使用案例
*/
public class Generic02 {
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        /*(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() {
        /*(7)重写实现的compare( )方法:先按照name排序,如果name相同,则按生日日期的先后排序。*/
            @Override
            public int compare(Employee o1, Employee o2) {
                /*①对输入的参数进行验证*/
                if(!(o1 instanceof Employee && o2 instanceof Employee))
                {
                    System.out.println("传入参数类型不正确!!!");
                    return 0;
                }
                /*②-1、比较name*/
                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());
                }
            }
        });
        /*(8)输出排序前arrarList*/
        System.out.println("======排序后======");
        System.out.println(arrayList);
    }
}

/*(2)创建Employee类*/
class Employee{
    /*Employee类的三个属性*/
    private String name;
    private double salary;
    private Mydate birthday;

    /*Employee类的构造器*/
    public Employee(String name, double salary, Mydate birthday){
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    /*Employee类所有属性的get和set方法*/
    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;
    }

    /*重写Employee类的toString()方法*/
    @Override
    public String toString() {
        return "\n"+"Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }
}

/*(1) 因为Employee类的属性birthday为MyDate类的对象,所以首先要创建MyDate类。*/
 class Mydate implements Comparable{

    /*MyDate类的三个属性*/
    private int year;
    private int month;
    private int day;

    /*MyDate类构造器*/
    public Mydate(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    /*MyDate类所有属性的get和set方法*/
    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;
    }

    /*重写MyDate类的toString()方法*/
    @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;
        }
    }
}

运行结果:
【Java】泛型经典使用案列_第2张图片

你可能感兴趣的:(泛型,java)