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];
  // 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.


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) { ... }




I think a basic null check will work.

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

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




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.



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).



  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.



All Articles