简体   繁体   中英

How to check If the next element in an array is null - Java

I'm creating quite a large, multiple class program and just need to find out if the next element in the array exists for one of my methods. (ie if i is the last element).

My code:

if (eMessageArray[i + 1] != null) {
    temp = stringShuffle(eMessageArray[i], eMessageArray[i + 1]);
    eMessageArray[i] = temp;
} else if (eMessageArray[i + 1] == null) {
    temp = stringShuffle(eMessageArray[i], "NULL");
    eMessageArray[i] = temp;
}

The problem is that when i points to the the last element of the array, then there is no element i+1 , because the array is not long enough. The solution is to stop iterating with i at the second last index, so that i+1 is always a valid index. This is done with the ...length - 1 as follows:

for (int i = 0; i < eMessageArray.length - 1; i++) { // important: - 1 to omit last index for i
    if (eMessageArray[i+1]!=null){
        temp = stringShuffle(eMessageArray[i], eMessageArray[i+1]);
    } else {
        temp=stringShuffle(eMessageArray[i], "NULL");
    }
    eMessageArray[i]=temp;
}

Generally when trying to access the array index out of bounds there might be some garbage values present instead, which would though not be null yet meaningless to be accessed. You would want to define the bounds of an array if you want to use it && provide that check inside your iteration for the bound range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM