[英]How do I check if an array element exists?
我正在寻找Java相当于PHP的isset() ;
int board[][]=new int[8][8];
...
if(isset(board[y][x]))
// Do something with board[y][x]
Java中是否存在这样的函数?
编辑:对不起,我的意思是我想检查board[100][100]
存在。 if(board[100][100])
会导致数组越界错误。
在Java中, int
数组被初始化为零值,因此您将无法判断它是否未设置,或者它是否设置为值0。
如果要检查它是否已设置,则应使用Integer
数组。 如果未设置该值,则它将为null
。
Integer[][] board = new Integer[8][8];
...
if (board[x][y] != null) { ... }
我认为基本的空检查会起作用。
String[] myArray = {"Item1", "Item2"};
for(int x =0; x < myArray.length; x++){
if(myArray[0] != null)
{
...do something
}
}
您可以创建一个方法来检查首先x,y是否在数组的边界内,以及该值是否为null。 我不相信有一个内置的数组方法,但有一些类似于.contains()的辅助函数用于ArrayLists。
可能最好不要使用int,你可以使用Integer,如果你真的必须把它作为一个int,但一般来说复杂的对象会更好(比如ChessPiece或其他东西)。 这样你就可以检查是否值== null(null表示它尚未设置)。
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没有等价物。 因为知道某些东西是否真的设置不仅仅是将一个值填充到一个位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.