泛型的使用细节
1. 给泛型指向的数据类型要求是引用类型,不能是基本数据类型
2.在给泛型指定具体类型后,可以传入类型或者其子类类型
3.泛型使用形式
泛型课堂练习
import java.util.ArrayList;
import java.util.Comparator;
public class TestGeneric03 {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee("jerry",22000,new MyDate(1,28,1995)));
employees.add(new Employee("tom",20000,new MyDate(3,20,1996)));
employees.add(new Employee("jean",22000,new MyDate(9,2,1994)));
employees.sort(new Comparator<Employee>() {
@Override
public int compare(Employee emp1, Employee emp2) {
//先按照name排序,如果name相同,则按生日日期的先后排序
//先对传入的参数进行验证
if (!(emp1 instanceof Employee && emp2 instanceof Employee)){
System.out.println("类型不正确...");
return 0;
}
//比较name
int i = emp1.getName().compareTo(emp2.getName());
if ( i != 0){
return i;
}
//下面是对birthday的比较,因此我们最好把这个比较,放在MyDate类方法
//封装后,将来可维护性和复用性就大大增加
return emp1.getBirthday().compareTo(emp2.getBirthday());
}
});
System.out.println("对雇员进行排序后");
System.out.println("employees = " + employees);
}
}
public class MyDate implements Comparable<MyDate>{
private int month;
private int day;
private int year;
public MyDate(int month, int day, int year) {
this.month = month;
this.day = day;
this.year = year;
}
@Override
public String toString() {
return "MyDate{" +
"month=" + month +
", day=" + day +
", 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;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@Override
public int compareTo(MyDate o) {
int yearMinus = year - o.getYear();
if (yearMinus != 0) {
return yearMinus;
}
//如果year相同,比较month
int monthMinus = month - o.getMonth();
if (monthMinus != 0) {
return monthMinus;
}
return day - o.getDay();
}
}
public class Employee {
private String name;
private double sal;
private MyDate birthday;
@Override
public String toString() {
return "\nEmployee{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
public Employee(String name, double sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
}