If (variable == [any item in the collection]) in Java

Say I have an array of primitives or a list of objects, it doesn't matter if there is a short way to do this 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 } } 

Thanks!

+4
source share
4 answers

Do you need to use arrays? Why not switch to the API Collection ?

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

Returns true if this collection contains the specified item. 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 request can be answered in O(1) or O(log N) .

+7
source

If you want your search to be O (1), you need to pass the data in an associative array or hash table. Otherwise, you have to cross each element. The contains method will simply rotate and move around your list.

+8
source
 import java.util.*; int index = Arrays.binarySearch(array, find_this); 

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

Another method I just came up with: to save the 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 it doesn't seem to work with arrays of primitive types.

+2
source

Check apache commons ListUtils and ArrayUtils , which contains the method.

+1
source

Source: https://habr.com/ru/post/1303181/


All Articles