62,620
社区成员
发帖
与我相关
我的任务
分享
package csdn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionTest {
/**
* public static <T> int binarySearch(List<? extends Comparable<? super T>> list,
T key)
* 上面的参数注意理解? extends Comparable<? super T>表示list里面放的
* 对象必须是实现了Comparable接口的
* @param list
* @param key
*/
public static void testBinarySearch(List<Person> list,Person key) {
System.out.println("index:"+Collections.binarySearch(list, key));
}
/**public static <T> int binarySearch(List<? extends T> list,
T key,
Comparator<? super T> c)
*
*/
public static void testBinarySearchWithComparator(){
}
public static void main(String args[]) {
List<Person> perList = new ArrayList<Person>();
perList.add(new Person("a",20,100));
perList.add(new Person("b",19,85));
perList.add(new Person("c",35,120));
perList.add(new Person("d",10,110));
perList.add(new Person("e",33,145));
perList.add(new Person("f",5,132));
System.out.println(perList);
testBinarySearch(perList,new Person("a",10,120));//排序前查找,不可预料的结果
Collections.sort(perList);//排序后
System.out.println(perList);
testBinarySearch(perList,new Person("a",10,120));//
}
}
/**
* 人这个对象实现了Comparable,可以被比较,collections.sortList方法会调用里面的
* compareTo方法
* @author ydy
*
*/
class Person implements Comparable<Person>{
String name;
int age;
int weight;
public Person(String name,int a,int w){
this.name=name;
age=a;
weight=w;
}
/**
* 这里以age作为比较,升序排列,你也可以由weight做为比较
*/
@Override
public int compareTo(Person o) {
if(age==o.age)
return 0;
if(age<o.age){
return -1;//return-1的排前面
}else return 1;
}
public String toString(){
return "name:"+name+" age:"+age+ " weight:"+weight;
}
}