Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java check if array[] item exists

Tags:

I am downloading some data into a String array. Let's say ImageLinks. How do I check if a item in array exist?

I am trying

if(ImageLinks[5] != null){} 

but it gives me ArrayIndexOutOfBoundsException. (Because there are really no 5 link in the array)

like image 434
artouiros Avatar asked Oct 15 '12 14:10

artouiros


People also ask

How do you check if a string exists in an array Java?

Since java-8 you can now use Streams. String[] values = {"AB","BC","CD","AE"}; boolean contains = Arrays. stream(values). anyMatch("s"::equals); To check whether an array of int , double or long contains a value use IntStream , DoubleStream or LongStream respectively.

How do you check if an array has a certain value?

For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.

How do you check if an array does not contain a value Java?

To check if an array doesn't include a value, use the logical NOT (!) operator to negate the call to the includes() method. The NOT (!) operator returns false when called on a true value and vice versa.


1 Answers

To prevent the ArrayIndexOutOfBoundsException, you can use the following:

if(ImageLinks.length > 5 && ImageLinks[5] != null) {     // do something } 

As the statements in the if are checked from left to right, you won't reach the null check if the array doesn't have the correct size.

It's quite easy to generalise for any scenario.

like image 119
Baz Avatar answered Sep 29 '22 08:09

Baz