java中对象比较大小
1.实现conparable接口
2.匿名内部类(用lambda的方式写)
class Person implements Comparable<Person> { private String name; private int age; public Person(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 "Person [name=" + name + ", age=" + age + "]"; } /** * TODO重写compareTo方法实现按年龄来排序 */ @Override public int compareTo(Person o) { // TODO Auto-generated method stub return this.age-o.getAge()==0?this.name.compareTo(o.getName()):this.age-o.getAge(); } public static void main(String[] args) { Person[] array=new Person[5]; array[0]=new Person("cijun",2); array[1]=new Person("biu",1); array[2]=new Person("aiu",1); array[3]=new Person("ciu",1); array[4]=new Person("bhao",5); // Arrays.sort(array);//法一 Arrays.sort(array,(o1,o2)->{ return o1.age==o2.age?o1.name.compareTo(o2.name):o1.age-o2.age;}); System.out.println(Arrays.toString(array)); } }
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/10529738.html