public class Student implements Comparable<Student>{ private String id; private String name; private int age;java
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方法 */
}apache
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));ide
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這篇 有提供這個方法實例this
在student實體實現了 排序 還有一種排序完在實現,不排序,還不能找到正確的序號,很神奇!google
package list;code
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;blog
import org.apache.commons.lang3.math.NumberUtils;排序
import com.google.common.collect.Lists;get
public class IndexList {io
@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); }
}