Reputation: 1163
I have a String[]
and I would like to check if an index exists in it (such as String[3]).
How can I go about doing this?
Upvotes: 2
Views: 7889
Reputation: 639
public boolean DoesIndexExists(String []arr, int index){
if( arr != null && index >= 0 && index < arr.length && )
return true;
return false;
}
Upvotes: 0
Reputation: 41200
public boolean indexExists(String[] array,int index){
if(array!=null && index >= 0 && index < array.length)
return true;
else
return false;
}
Upvotes: 4
Reputation: 500367
if (arr != null && i >= 0 && i < arr.length) {
// arr[i] exists
}
If arr
is an array of objects, you may also need to check whether arr[i]
is null:
if (arr != null && i >= 0 && i < arr.length && arr[i] != null) {
// arr[i] exists and is not null
}
Upvotes: 12
Reputation: 25950
An existing index doesn't necessarily mean a non-null array entry, be careful.
String[] array = ...
int index = 3;
if(array.length > index && index >= 0)
// it exists.
Upvotes: 4