标签:highlight else quicksort 自己 基本数据类型 二次排序 优点 tag 外部
实现Comparable接口要重写compareTo方法, 在compareTo方法里面实现比较
1 public class Person implements Comparable<Person>{ 2 String name; 3 int age; 4 int weight; 5 public Person(String name, int age,int weight) 6 { 7 super(); 8 this.name = name; 9 this.age = age; 10 this.weight = weight; 11 } 12 public String getName() 13 { 14 return name; 15 } 16 public int getAge() 17 { 18 return age; 19 } 20 public int getWeight() 21 { 22 return weight; 23 } 24 @Override 25 public int compareTo(Person p) 26 { 27 if(this.age - p.age == 0){ 28 return this.weight - p.weight; 29 } 30 else 31 {return this.age - p.age;} 32 }
public class UserInfo {
public static void main(String[] args)
{
Person[] people=new Person[]{
new Person("xujian", 20,60),
new Person("xiewei", 10,70),
new Person("xiewei", 20,70)};
System.out.println("排序前");
for (Person person : people)
{
System.out.println(person.getName()+":"+person.getAge()+‘:‘+person.weight);
}
Arrays.sort(people);
System.out.println("\n排序后");
for (Person person : people)
{
System.out.println(person.getName()+":"+person.getAge()+‘:‘+person.weight);
}
int[] array = {123,2,3,4};
Integer[] array1 = {123,2,3,4};
}
实现Comparator需要重写 compare 方法
public class PersonComparator {
public static void main(String[] args) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("xujian", 20,60));
personList.add(new Person("xiewei", 10,70));
personList.add(new Person("xiewei", 20,70));
System.out.println("排序前");
for (Person person : personList)
{
System.out.println(person.getName()+":"+person.getAge()+‘:‘+person.weight);
}
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if(o1.age - o2.age == 0){
return o1.weight - o2.weight;
}
else
{return o1.age - o2.age;}
}
});
System.out.println("排序前");
for (Person person : personList)
{
System.out.println(person.getName()+":"+person.getAge()+‘:‘+person.weight);
}
}
}
以上的例子中用到的是,稳定排序,先排序年龄,在年龄相同的情况下然后按照体重排序。
总结:
标签:highlight else quicksort 自己 基本数据类型 二次排序 优点 tag 外部
原文地址:https://www.cnblogs.com/xujiangxi/p/12356611.html