Java implements sorting of output Objects Based on properties and java sorting of output objects

Source: Internet
Author: User

Java implements sorting of output Objects Based on properties and java sorting of output objects

Package com. wms; import java. util. arrays; public class DogAgeSort {public static void main (String [] args) {Dog [] dogs = {new Dog ("yellow", 2), new Dog ("green ", 1), new Dog ("", 3), new Dog ("", 6)}; Arrays. sort (dogs, new DogComparator (); for (Dog dog: dogs) {System. out. println (dog );}}}
package com.wms;public class Dog {    private String name;    private int age;            public Dog() {}    public Dog(String name, int age) {        super();        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "Dog [name=" + name + ", age=" + age + "]";    }    }
package com.wms;import java.util.Comparator;public class DogComparator implements Comparator<Dog>{    public int compare(Dog o1, Dog o2) {        if(o1.getAge()<o2.getAge()){            return -1;        }else if(o1.getAge()>o2.getAge()){            return 1;        }else{            return 0;        }    }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.