So I have written some code which tells whether a certain Integer is within a list of integers. I tried to do this with a comparable type instead of 'integer' type, but I realised that this wouldn't work as we could have say a String and Integer in the same list. I want to be able to have comparables of all the same type, but not limited to just Integers... Does anyone know how I could do this? I'm not very confident with using interfaces as input parameters. This is my code:
package Recursion; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class BinarySearch { // Takes in a sorted list (ascending order) of comparable objects // and finds whether a certain object is in that list using binary // search method. public static void main(String[] args){ ArrayList<Integer> l = new ArrayList<Integer>(); l.add(3); l.add(10); l.add(30); l.add(502); System.out.println(l); Scanner s = new Scanner(System.in); while(s.hasNextInt()){ int n = s.nextInt(); System.out.print(BinarySearch.search(l, n)); } } //Check whether something is in the list public static boolean search(List<Integer> al, Integer c){ //Current one we are looking at Integer pivot = al.get(al.size()/2); if (c.equals(pivot)){ return true; } else if (c.compareTo(pivot) == -1){ if (al.size()/2 == 0){ //if our pivot is the first value in the sorted list return false; // no more to see } else { return search(al.subList(0,al.size()/2),c); } } else { if(al.size()/2 == 0){ return false; } else { return search(al.subList(al.size()/2,al.size()),c); } } } }