Collections.binarySearch的两个用法

public class Student implements Comparable<Student>{ private String id; private String name; private int age;

public Student(String id,String name,int age){
    this.id = id;
    this.name = name;
    this.age = age;
}

public boolean equals(Object obj){
    if(obj == null){
        return false;
    }
    
    if(this == obj){
        return true;
    }
    
    if(obj.getClass() != this.getClass()){
        return false;
    }
    
    Student student = (Student)obj;
    if(!student.getName().equals(getName())){
        return false;
    }
    
    return true;
}

public int compareTo(Student student) {
    return this.age - student.age;
}

/** 省略getter、setter方法 */

}

public static void main(String[] args){ List<Student> list = new ArrayList<>(); list.add(new Student("1", "chenssy1", 24)); list.add(new Student("2", "chenssy1", 26));

    Collections.sort(list);   //排序
    
    Student student = new Student("2", "chenssy1", 26);
    
    //检索student在list中的位置
    int index1 = list.indexOf(student);
    int index2 = Collections.binarySearch(list, student);
    
    System.out.println("index1 = " + index1);
    System.out.println("index2 = " + index2);
}

http://cmsblogs.com/?p=1242这篇 有提供这个方法实例

在student实体实现了 排序 还有一种排序完在实现,不排序,还不能找到正确的序号,很神奇!

package list;

import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;

import com.google.common.collect.Lists;

public class IndexList {

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
	List list = Lists.newArrayList();
	list.add(2);
	list.add(3);
	list.add(4);
	list.add(3);
	list.add(0);
	// Arrays.binarySearch(arg0, arg1)
	Comparator c = new Comparator(){
		@Override
		public int compare(Object o1, Object o2) {
			return NumberUtils.toInt(o1.toString())-NumberUtils.toInt(o2.toString());
		}
	};
	Collections.sort(list, c);
	int indexFirst = Collections.binarySearch(list, 0, null);
	System.out.println("indexFirst" + indexFirst);
	// create arraylist
	ArrayList<String> arlst = new ArrayList<String>();

	// populate the list
	arlst.add("TP");
	arlst.add("PROVIDES");
	arlst.add("QUALITY");
	arlst.add("TUTORIALS");

	// search the list for key 'QUALITY'
	int index = Collections.binarySearch(arlst, "QUALITY");

	System.out.println("'QUALITY' is available at index: " + index);

}

}

转载于:https://my.oschina.net/u/1052192/blog/688578

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值