我把排序语句注释掉输出索引是-2还报下标越界异常,为什么?
import java.util.Arrays;
class ArrayTest
{
public static void main(String[] args)
{
Student[] ss=new Student[]{
new Student(1,"zhangsan"),
new Student(4,"lisi"),
    new Student(2,"wangwu"),
new Student(3,"mybole")};
/* Student[] ss=new Student[4];
ss[0]=new Student(1,"zhangsan");
ss[1]=new Student(3,"lisi");
    ss[2]=new Student(2,"wangwu");
ss[3]=new Student(4,"mybole");*/
// Arrays.sort(ss);
/* for(int i=0;i<ss.length;i++)
{
System.out.println(ss[i]);
}*/
int index=Arrays.binarySearch(ss,ss[2]);
System.out.println("index="+index);
System.out.println(ss[index]);
}
}
class Student implements Comparable
{
int num;
String name;
Student(int num,String name)
{
this.num=num;
this.name=name;
}
public String toString()
{
return "number="+num+","+"name="+name;
}
public int compareTo(Object o)
{
Student s=(Student)o;
int result=num>s.num ? 1 : (num==s.num ? 0 : -1);
if(0==result)
{
result=name.compareTo(s.name);
}
return result;
}
}
希望多解释清楚这个问题

解决方案 »

  1.   

    Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by Sort(Object[]), above) prior to making this call. If it is not sorted, the results are undefined. (If the array contains elements that are not mutually comparable (for example,strings and integers), it cannot be sorted according to the natural order of its elements, hence results are undefined.) If the array contains multiple elements equal to the specified object, there is no guarantee which one will be found. 以前学数据结构,书上的折半查找是建立在排好序之后滴. 书X,赫赫