About the use Comparable

As a road just super junior programmer, today finally taking their first step, write a blog. I have moved to tears.

Today saw the watch face questions using a Comparable, only to find himself does not seem to have used this interface, the specific use of this interface is how I read a few comparable in the blog, I felt this thing should be recorded, also I hope that they can get to grow.

 

First, we give an example of the arrangement int array, an array if there are so few elements, I hope he will be from small to large, do not use bubble sort algorithms, direct use of java class Arrays carried out using this method you can of elements in the array for direct ordering, very convenient.

int[] array = {9,5,7,5,31,7};
        Arrays.sort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
 }
结果:5 5 7 7 9 31

 

If there is now a requirement, there is an entity class User, User class has three attributes, id, name, price

class User{
    private int id;
    private String name;
    private int price;

You need to sort (just as int array sort of the same) by price in ascending order. So we did this time, or you can use the sort () method, except that, before using an array of type int, this needs to be changed, an array of type User sort by price, this time you need to let go User achieve comparable interfaces, wherein the method of rewriting, only the return value of -1, 0, 1 compareTo method

class User implements Comparable<User>{

    private int id;
    private String name;
    private int price;

    public User(int id, String name, int price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    @Override
    public int compareTo(User o) {
        if(this.price>o.price){
            return 1;
        }else if(this.price<o.price){
            return -1;
        }else {
            return 0;
        }
    }
}

Finally, a few new object into an array of type User comparison, sort () will be able to sort

        User[] users = new User[3];
        users[0] = new User(1,"寿司",29);
        users[1] = new User(2,"蛋挞",21);
        users[2] = new User(3,"牛排",25);
        Arrays.sort(users);
        for (int i = 0; i < users.length; i++) {
            System.out.println(users[i]);
        } 
结果:    User{id=2, name='蛋挞', price=21}
          User{id=3, name='牛排', price=25}
          User{id= 1, name = 'sushi', price = 29}                    

 

Guess you like

Origin www.cnblogs.com/Crush123/p/11580792.html