Reputation: 26085
I'm looking for Java's equivalent of PHP's isset();
int board[][]=new int[8][8];
...
if(isset(board[y][x]))
// Do something with board[y][x]
Does such a function exist in Java?
Edit: Sorry, what I meant is that I want to check if board[100][100]
exists or not. if(board[100][100])
would result in an array out of bounds error.
Upvotes: 4
Views: 17398
Reputation: 22637
In Java, int
arrays are initialized to a value of zero, so you won't be able to tell if it's been not set, or if it's set to a value of 0.
If you want to check if it's set, you should use an array of Integer
. If the value isn't set, it will be null
.
Integer[][] board = new Integer[8][8];
...
if (board[x][y] != null) { ... }
Upvotes: 6
Reputation: 8594
if (board[x][y] != null) {
// it's not null, but that doesn't mean it's "set" either. You may want to do further checking to ensure the object or primitive data here is valid
}
Java doesn't have an equiv. to isset because knowing if something is truly set goes beyond just stuffing a value into a location.
Upvotes: -1
Reputation: 61526
Probably better to not use int, you could use Integer if you really have to have it as an int, but generally speaking a complex object is going to be better (like a ChessPiece or something). That way you can check to see if the value == null (null means it has not been set).
Upvotes: 0
Reputation: 94429
I think a basic null check would work.
String[] myArray = {"Item1", "Item2"};
for(int x =0; x < myArray.length; x++){
if(myArray[0] != null)
{
...do something
}
}
Upvotes: 1
Reputation: 4032
You can create a method that checks that first the x, y is in the bounds of the array and if it is that the value is not null. I don't believe there is a built in method for array, but there are helper functions similar like .contains() for ArrayLists.
Upvotes: 0