数组对象排序

package day_23;

public class Product {
    private String name;
    private int price;

    public Product() {

    }

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

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
package day_23;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 数组对象排序
 */
public class Test2 {
    public static void main(String[] args) {
        Product [] product=new Product[5];
        product[0]=new Product("联想",5600);
        product[1]=new Product("华为",9800);
        product[2]=new Product("小米",7600);
        product[3]=new Product("戴尔",8700);
        product[4]=new Product("苹果",11100);

        //  1)输出对象数组
        System.out.println(Arrays.toString(product));

        //  2)对对象数组进行排序
        //    可以指定一个comparator比较器
        Arrays.sort(product, new Comparator<Product>() {
            //在匿名内部类中重写comparator接口的抽象方法,指定比较规则
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getPrice()-o2.getPrice();    //按价格升序   (降序:02-01)
            }
        });
        System.out.println(Arrays.toString(product));


    }
}

  

posted @ 2019-08-07 14:14  石乐智先生  阅读(757)  评论(0编辑  收藏  举报