views:

129

answers:

4

Let's say I have an array of primitives or a list of objects, doesn't matter, is there a short way of doing this kind of check:

if (a_primitive == any_item_in_my_collection) {
    // do something
}

or

if (an_object_ref.equals(any_item_in_my_collection)) {
    // do something
}

without doing this

for (int i = 0; i < myArray.length; i++) {
    if (a_primitive == myArray[i]) {
        // do something
    }
}

Thank you!

+7  A: 

Do you have to use arrays? Why not switch to Collection-based API?

Then you can use Collection.contains(Object o).

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

Depending on the implementation, this query can be answered in O(1) or O(log N).

polygenelubricants
+1  A: 

Check apache commons ListUtils and ArrayUtils which has contains method.

Teja Kantamneni
ListUtils is a red herring, according to the linked javadoc: there is no `contains` method or equivalent.
Stephen C
+8  A: 

If you want your lookup to be O(1) - you need to mantain the data in an associative array or hashtable. Otherwise, you're going to have to traverse each element. The contains method is just going to turn around and traverse your List for you.

Amir Afghani
Thanks, I just learned something new.
Slavko
+2  A: 
import java.util.*;

int index = Arrays.binarySearch(array, find_this);

(edit: only if array is sorted :) -- see http://www.exampledepot.com/egs/java.util/coll_FindInArray.html for details)

Another method I just thought up: to retain your original array, you can do: List<T> l = Arrays.asList(arr); where T is the type of the array, then you can do l.contains(o);. But this won't work with primitive type arrays, I guess.

Chris Dennett
Only works if array is sorted.
polygenelubricants