2

我正在尝试在 ArrayList 中进行二进制搜索,但 binarySearch 方法不适用于 Long 以及 Double 和 Float。我的代码是

import java.util.*;

 public class BinarySearchInArrayList
 {
     public static void main(String[]args)
     {
         ArrayList<Long> ar = new ArrayList();

         for(long l = 1;l<100000;l++)
         {
             ar.add(l);
         }

         System.out.println("arraylist: "+ar); 
         System.out.println("Which number's index do you want to know? ");
         Scanner scan = new Scanner(System.in);
         int p = scan.nextInt();
         int index = Collections.binarySearch(ar,p);
         System.out.println("number "+p+" has index "+index);
     }

当我使用 Integer 而不是 时Long,它工作正常,但我想用Long. 你能帮我吗?

4

1 回答 1

6
int p = scan.nextInt();
int index = Collections.binarySearch(ar,p);

上面应该是:

long index = Collections.binarySearch(ar,p);
long p = scan.nextLong();
于 2013-04-26T13:04:30.467 回答