Comparable接口的使用(自然排序)
1.String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式. String、包装类重写了compareTo()方法以后,进行了从小到大的排序。
2.重写compareTo(obj)规则:
如果当前对象this大于形参对象obj,则返回正整数。
如果当前对象this小于形参对象obj,则返回负整数。
如果当前对象this等于形参对象obj,则返回0
3.对于自定义类,如果需要排序,让自定义类实现Comparable接口,重写compareTo(obj)方法,在compareTo(obj)方法中指明如何排序。
public class Goods implements Comparable<Goods>{ private String name; private double price; public Goods(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } //按照价格从低到高排序,再按照产品名称从高到底排序 @Override public int compareTo(Goods o) { //方式一 if(this.price>o.price){ return 1; }else if(this.price<o.price){ return -1; }else { //return 0;
return -this.name.compareTo(o.name); } //方式二 //return Double.compare(this.price,o.price); } }
@Test public void test1(){ Goods[] arr = new Goods[4]; arr[0] = new Goods("bbb",35); arr[1]= new Goods("eee",15); arr[2]= new Goods("ddd",55); arr[3]= new Goods("aaa",25); Arrays.sort(arr); System.out.println(Arrays.toString(arr)); //[Goods{name='eee', price=15.0}, Goods{name='aaa', price=25.0}, Goods{name='bbb', price=35.0}, Goods{name='ddd', price=55.0}] }
标签:Comparable,Goods,name,Comparator,price,arr,public,比较,String From: https://www.cnblogs.com/ixtao/p/16600487.html