简体   繁体   中英

Missing array check in 2D array - Java

I'm solving a problem where I am given a 2D array. The problem is, it is possible for one of the two arrays not to exist in the given 2D array.

I figured I could do a simple length check or null check but neither of those work. I get an arrayIndexOutOfBounds exception either way.

String smartAssigning(String[][] information) {
int[] employee1 = new int[3];
int[] employee2 = new int[3];
String name1 = "";
String name2 = "";

if(information[1].length <= 0 || information[1] == null)
{ return information[0][0];}

Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
at _runefvga.smartAssigning(file.java on line 7)
... 6 more

the first array at index 0 exists but the second array at index 1 does not exist. Is there another way to check for this?

information.length will return the number of arrays that are contained. information[n].length will return the length of the array at index n . When you check if(information[1].length <= 0 ... you're checking to see if there is a second array and what the length of that array is. If there isn't a second array, you will get an out of bounds.

Try:

for(String[] array : information) {
    //do something...
}

You need to take in account the order in which this conditions are checked.

You wrote:

if(information[1].length <= 0 || information[1] == null)

So first information[1].length <= 0 is checked and only if this is false than information[1] == null is checked.

The second condition makes no sense, if information[1] == null than there is already an Exception thrown when evaluating information[1].length .

So you need to switch the order to:

if(information[1] == null || information[1].length <= 0)

The second array does not exists, so information[1] == null is true

A 2-dimensional array in Java is actually just an array of arrays. Thus you need to check both the length of the "outer" array (the array of arrays) and the "inner" arrays (the arrays of int in your case). Unfortunately from your code it is not clear what you want to do, so depending on your goal and what you know about your callers (eg can information itself be null) you may want to check some or all of the following:

information!=null
information.length
information[x]!=null
information[x].length

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