madcrazydrumma madcrazydrumma - 5 months ago 10
Java Question

Is there a better way of creating an "abstract" linear search?

so I'm trying to write a linear search which could be used for most non-primitive data types.

Here is the code I'm using:

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


I was wondering if there is a better way this could be done, or a neater way. N.B. I am just looking to use a linear search algorithm

Thanks

Answer

You could use List#contains for a linear search. Also, there's no need for Comparable in this case.

public static <T> boolean search(T needle, T[] haystack) {
    return Arrays.asList(haystack).contains(needle);
}

Note: Arrays.asList returns a List view of the array. It won't make a copy.