import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person implements Comparable<Person>
{
String name;
int age;
// 为方便,没有写get、set方法
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return this.name + "----" + this.age;
}
public int compareTo(Person p)
{// 安装姓名排序
int num;
return (num = this.name.compareTo(p.name)) == 0 ? this.age - p.age : num;
}
}
public class Main
{
public static void main(String[] args)
{
ArrayList<Person> arrayList = new ArrayList<Person>();
arrayList.add(new Person("ZhangSan", 23));
arrayList.add(new Person("LiSi", 25));
arrayList.add(new Person("WangWu", 18));
arrayList.add(new Person("ZhaoLiu", 32));
arrayList.add(new Person("ZhangSan", 23));
arrayList.add(new Person("LiSi", 23));
Collections.sort(arrayList, new Comparator<Person>()
{// 匿名内部类
public int compare(Person p1, Person p2)
{// 按照年龄排序
int num;
return (num = p1.age - p2.age) == 0 ? p1.name.compareTo(p2.name) : num;
}
});
// Collections.sort(arrayList);
System.out.println(arrayList);
int num;
num = Collections.binarySearch(arrayList, new Person("LiSi", 23)); //LiSi,23这个人集合中有啊
System.out.println(num);
num = Collections.binarySearch(arrayList, new Person("ZhangSan", 23));
System.out.println(num);
num = Collections.binarySearch(arrayList, new Person("ZhaoLiu", 32));
System.out.println(num);
}
}
我的运行结果
[WangWu----18, LiSi----23, ZhangSan----23, ZhangSan----23, LiSi----25, ZhaoLiu----32]
-1 //搞不明白这里为什么是-1
2
5
|
|