当我尝试编译这个二进制搜索程序时,我收到一条消息,说我有未经检查和不安全的操作。我查看了stackoverflow上的其他帖子,但我无法弄清楚如何修复我的代码。谢谢!
public binarySearch()
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0;i<10;i++)
{
int rand = (int)(Math.random()*10);
list.add(rand);
System.out.print(list.get(i)+"\t");
if ((i+1)%10==0) System.out.println();
}
System.out.println("\n"+search(sort(list),0));
}
public ArrayList sort(ArrayList<Integer> listNum)
{
for (int i=0;i<listNum.size()-1;i++)
{
int min=10000;
int index=0;
for (int j=i;j<listNum.size();j++)
if (listNum.get(j)<min)
{
min=listNum.get(j);
index=j;
}
int temp = listNum.get(i);
listNum.set(i,listNum.get(index));
listNum.set(index,temp);
}
return listNum;
}
public boolean search(ArrayList<Integer> listNum, int num)
{
//need to sort list
int low = 0;
int high = listNum.size()-1;
while (low<=high)
{
int mid = (low+high)/2;
int midValue = listNum.get(mid);
if (num<midValue)
high = mid-1;
if (num>midValue)
low = mid+1;
if (num==midValue)
return true;
}
return false;
}
public static void main (String args[])
{
binarySearch app = new binarySearch();
}
答案 0 :(得分:3)
方法返回应该是
public ArrayList<Integer> sort(ArrayList<Integer> listNum)
答案 1 :(得分:1)
您的排序方法返回原始类型,因此编译器警告。使sort方法返回参数化类型的ArrayList。
public ArrayList<Integer> sort(ArrayList<Integer> listNum)
有用的帖子: