artouiros
artouiros

Reputation: 3987

Java check if array[] item exists

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)

Upvotes: 28

Views: 101664

Answers (6)

Alexis Gamarra
Alexis Gamarra

Reputation: 4432

if (ImageLinks != null && Stream.of(ImageLinks).anyMatch(imageLink-> imageLink != null)) {
//An item in array exist
}

Upvotes: 0

Vivek
Vivek

Reputation: 1680

Write a static function

public static boolean indexInBound(String[] data, int index){
    return data != null && index >= 0 && index < data.length;
}

Now, give it a call in your code

if(indexInBound(ImageLinks, 5) && ImageLinks[5] != null){
   //Your Code
}

Upvotes: 8

Edward Vaghela
Edward Vaghela

Reputation: 19

The reason its fails is the array has less than 6 elements.

Check first the array has correct number of elements, and then check the element exists in array.

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

Upvotes: 1

Baz
Baz

Reputation: 36904

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.

Upvotes: 38

banjara
banjara

Reputation: 3890

yes there are less than 6 elements ImageLinks[5] refers to 6th element as array index in java starts from 0

Upvotes: 0

kosa
kosa

Reputation: 66677

Make sure array is of that length before doing lookup

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

Upvotes: 6

Related Questions