List list = new ArrayList();
list.add(new Person("lcl", 28));
Person person=new Person("wqx", 29);
list.add(person);
list.add(new Person("kx", 23));
System.out.println(Collections.binarySearch(list,person));//错误在这里
为什么会出现以下异常:
java.lang.ClassCastException
at java.util.Collections.indexedBinarySearch(Collections.java:210)
at java.util.Collections.binarySearch(Collections.java:198)
at util.ListSort.main(ListSort.java:36)

解决方案 »

  1.   

    你的Person类没有实现Comparable接口,over
      

  2.   

    而且list也没排序,就算实现了接口,结果也不会对
      

  3.   

    为什么这样也会出错?
                      ArrayList list = new ArrayList();
    list.add(new Person("lcl", 28));
    Person person=new Person("wqx", 29);
    list.add(person);
    list.add(new Person("kx", 23));
                      Collections.sort(list);
    for (int i = 0; i < list.size(); i++) {
    Person p = (Person) list.get(i);
    System.out.print(p.getName() + "  ");
    System.out.println(p.getAge());
    }
      

  4.   

    如果要实现Comparable 怎么写,我这样为什么不对,请高手指点,谢谢.class Person implements Comparable
    {
        String name = "";
        Integer ageInt = null;
        
        //抽象方法的继承
        public int compareTo(Object o)
        {
         return compareToThis((Integer)o);
        }
        
        public int compareToThis(Integer anotherInteger) 
        {
            int i = anotherInteger.compareTo(ageInt);
            
            return i;
        }    
        public Person(String name, Integer age)
        {
            this.name = name;
            //this.age = age;
            this.ageInt = age;
        }
        
        public String getName()
        {
            return this.name;
        }
        
        public Integer getAge()
        {
            return this.ageInt;
        }
    }