marek marek - 2 months ago 10
Java Question

How can I do binary search in java ArrayList<Long>?

I am trying to make binary search in ArrayList, but the binarySearch method does not work for Long, as well as Double and Float. My code is

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);
}


When I use Integer instead of
Long
, it works fine, but I want to make it with
Long
. Can you help me, please?

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

Above should be:

long index = Collections.binarySearch(ar,p);
long p = scan.nextLong();