1

I have a problem that I'm stuck on. Namely, I have a for loop that goes through an integer array and compares it to another integer. If any integer in the array is the same as the given integer it's true, otherwise, it's false.

public static boolean search(int item, int[] arr) { 
    for (int i = 0; i < arr.length; i++) { 
        if (arr[i] == item) { 
        return true; 
        } 
    } 
    return false; 
 }

What I'm wondering is how could I modify this code so that I could input any type of item and array (ie String or int or double, etc) and have it do the same thing. I attempted to do something like:

public static boolean search(Object item, Object[] arr) { 
        for (int i = 0; i < arr.length; i++) { 
            if (arr[i].equals(item)) { 
                return true; 
            } 
        } 
        return false; 
    }

However this doesn't work for ints. If possible, could you keep this at a more conceptual level rather than straight giving me the answer as I would like to code and debug it myself. Conceptually I just want to know what is the generic form of everything (int, String, etc).

Thanks!

1 Answers1

0

This is what generics can be used for.

public static <T extends Comparable<T>> boolean search(T item, T[] arr) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i].compareTo(item) == 0) {
            return true;
        }
    }
    return false;
}

Have a look at the Java Tutorials: http://docs.oracle.com/javase/tutorial/java/generics/#

Giving just the hint to generics would not have been a great difference, that's why I included the code. Nevertheless, check for the usage of the compareTo() method, which is key to the solution (besides generics). And maybe dive into binary search.

thertweck
  • 1,120
  • 8
  • 24
  • It's not going to work with int, long and double, which are not even objects. – Oleg Gryb Jul 19 '14 at 21:53
  • http://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types – Himanshu Tyagi Jul 19 '14 at 21:53
  • Yes it does. As it is necessary with the whole collection API, the primitive wrappers Double, Long, Integer, ... can be used - also these classes implement Comparable. A generic solution with primitive types is not possible in Java (as there is no concept like templates in C++). – thertweck Jul 19 '14 at 21:55
  • if wrappers are to be used then the code given in question will work just fine! – Himanshu Tyagi Jul 19 '14 at 21:59