Date 比较器阶段习题

1: 将字符串"2017-08-13" 转化为sql.Date

 

 

 

2: 自定义Person类 如何实现自然排序(按照姓名从小到大排序)

public class HomeTestOne {
    public static void main(String[] args) {

        PersonTestOne [] arr = new PersonTestOne[2];
        arr[0] = new PersonTestOne("老王");
        arr[1] = new PersonTestOne("老李");
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        
    }
}



class PersonTestOne implements Comparable {
//    private  int age;
    private String name;
    @Override
    public int compareTo(Object obj){
        if(obj instanceof PersonTestOne){
            PersonTestOne personObj = (PersonTestOne) obj;
            return this.name.compareTo(personObj.name);
        }

        throw  new RuntimeException("输入的内容不对");
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "PersonTestOne{" +
                "name='" + name + '\'' +
                '}';
    }
    public PersonTestOne(){}
    public PersonTestOne(String name){
        this.name = name;
    }
}
自然排序姓名

 

 

3: 自定义Person 按照自定义排序 实现按照年龄排序

public class ComparatorTestT {
    public static void main(String[] args) {
        PersonCom [] arr = new PersonCom[2];
        arr[0] = new PersonCom(13);
        arr[1] = new PersonCom(14);
        Arrays.sort(arr, new Comparator<PersonCom>() {
            @Override
            public int compare(PersonCom o1, PersonCom o2) {
                if(o1 instanceof  PersonCom && o2 instanceof  PersonCom){
                    PersonCom p1 = (PersonCom) o1;
                    PersonCom p2 = (PersonCom) o1;
                    return Double.compare(p1.getAge(),p2.getAge());  // 从小到大 
//                    return -Double.compare(p1.getAge(), p2.getAge()); // 从大到小
                }
                throw  new RuntimeException("输入的对象不对");
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}

class PersonCom {
    private  int age;

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "PersonCom{" +
                "age=" + age +
                '}';
    }
    public PersonCom(int age){
        this.age = age;
    }
}
按照年龄排序
posted @ 2020-01-09 16:54  可爱的红领巾  阅读(274)  评论(0编辑  收藏  举报