泛型课堂练习题(韩顺平老师)
定义Employee类
(1)该类包含:private成员变量name,sal,birthday,其中birthday为MyDate类的对象;
(2)为每一个属性定义getter,setter方法;
(3)重写toString方法输出name,sal,birthday
(4)MyDate类包含:private成员变量year,month,year;并为每一个属性定义getter,setter方法;
(5)创建该类的3个对象,并把这些对象放入ArrayList集合中(ArrayList需使用泛型来定义),对集合中的元素进行排序,并遍历输;
排序方式:调用ArrayList的sort方法,传入Comparator对象[使用泛型],先按照name排序,如果name相同,则按生日日期的先后排序。
Employee:
package ch05;
public class Employee {
private String name;
private double sal;//薪水
private MyDate 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;
}
@Override
public String toString() {
return "\nEmployee [name=" + name + ", sal=" + sal + ", birthday=" + birthday + "]";// \n换行
}
}
GenericExercise02:
package ch05;
import java.util.ArrayList;
import java.util.Comparator;
@SuppressWarnings({"all"})
public class GenericExercise02 {
public static void main(String[] args) {
ArrayList<Employee>employees = new ArrayList<>();
employees.add(new Employee("tom", 20000, new MyDate(2000, 11, 11)));
employees.add(new Employee("jack", 12000, new MyDate(2001, 12, 12)));
employees.add(new Employee("hsp", 5000, new MyDate(1980, 10, 10)));
System.out.println("employees=" + employees);
employees.sort(new Comparator<Employee>() {
@Override
public int compare(Employee emp1,Employee emp2) {
if(!(emp1 instanceof Employee && emp2 instanceof Employee)) {
System.out.println("类型不正确...");
return 0;
}
int i = emp1.getName().compareTo(emp2.getName());
if(i != 0) {
return i;
}
return emp1.getBirthday().compareTo(emp2.getBirthday());
}
});
System.out.println("==对雇员进行排序==");
System.out.println(employees);
}
}
MyDate:
package ch05;
public class MyDate implements Comparable<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 "MyDate [year=" + year + ", month=" + month + ", day=" + day + "]";
}
@Override
public int compareTo(MyDate o) {
int yearMinus = year - o.getYear();
if(yearMinus != 0) {
return yearMinus;
}
int monthMinus = month - o.getMonth();
if(monthMinus != 0) {
return monthMinus;
}
return day - o.getDay();
}
}