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?
int p = scan.nextInt();
int index = Collections.binarySearch(ar,p);
Above should be:
long index = Collections.binarySearch(ar,p);
long p = scan.nextLong();
I'd recommend using Apache's ArrayUtils for this:
It offers this method:
static int indexOf(long[] array, long valueToFind, int startIndex)
Which finds the index of the given value in the array starting at the given index.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.