日期:2014-05-20  浏览次数:20711 次

Collections binarySearch 问题
将这句List<Food> list = new ArrayList<Food>()
改成这个却没有问题..?
List list = new ArrayList ()

为什么会这样?


---------- Java Compiler ----------
t1.java:25: cannot find symbol
symbol : method binarySearch(java.util.List<Food>,Food)
location: class java.util.Collections
int result = Collections.binarySearch(list, f[0]);
^
Note: t1.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

Output completed (0 sec consumed)


Java code
import java.util.*;

class  t1
{
    public static void main(String[] args) 
    {


        List<Food> list = new ArrayList<Food>();

        Vector<String> list2 = new Vector<String>();
        Food[] f = new Food[8];

        String []name ={"Q", "F", "B", "K", "J", "A", "G", "H"};

        for(int i=0; i<f.length; i++){
            f[i] = new Food(name[i]);
            list.add(f[i]);
            list2.add(name[i]);
        }
        

        Collections.sort(list);

        int result = Collections.binarySearch(list, f[0]);
        System.out.println("Found:" + result);

    }
}

class Food implements Comparable
{
    String name;

    public Food(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    
    public int compareTo(Object o) {
        if(this.name.compareToIgnoreCase(((Food)o).getName()) > 0)
            return 1;
        else if(this.name.compareToIgnoreCase(((Food)o).getName()) < 0)
            return -1;
        else
            return 0;
    }
}


------解决方案--------------------
是用的jdk5.0或以上吗