How can I check if an array element exists?

I'm looking for the Java equivalent of PHP isset () ;

int board[][]=new int[8][8];
...
if(isset(board[y][x]))
  // Do something with board[y][x]

      

Does such a feature exist in Java?

Edit: Sorry, I meant I want to check if it exists board[100][100]

or not. if(board[100][100])

will result in an out of bounds error.

+3


source to share


5 answers


In Java, arrays are int

initialized to zero, so you won't be able to tell if it wasn't set or set to 0.

If you want to check if it is set, you must use an array Integer

. If the value is not set, it will be null

.



Integer[][] board = new Integer[8][8];
...
if (board[x][y] != null) { ... }

      

+6


source


I think a basic null check will work.



String[] myArray = {"Item1", "Item2"};

for(int x =0; x < myArray.length; x++){
    if(myArray[0] != null)
    {
      ...do something
    }
}

      

+1


source


You can create a method that first checks that x, y is within the bounds of the array, and if it is not null. I don't believe there is a built-in method for an array, but there are helper functions similar to .contains () for ArrayLists.

0


source


It's probably best not to use int, you can use Integer if you really need to have it as an int, but generally speaking a complex object would be better (like ChessPiece or whatever). This way you can check if value == null (null means it was not set).

0


source


  if (board[x][y] != null) {
    // it not null, but that doesn't mean it "set" either.  You may want to do further checking to ensure the object or primitive data here is valid
  }

      

Java has no equiv. to isset because knowing whether or not something is actually set goes beyond just adding a value to a location.

-1


source







All Articles