[英]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.