java 如何检查数组元素是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9899563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if an array element exists?
提问by Leo Jiang
I'm looking for Java's equivalent of PHP's isset();
我正在寻找 Java 的等价于 PHP 的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?
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.
编辑:对不起,我的意思是我想检查是否board[100][100]
存在。if(board[100][100])
会导致数组越界错误。
回答by Jeffrey Blattman
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.
在 Java 中,int
数组被初始化为零值,因此您将无法判断它是否未被设置,或者它是否被设置为值 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
. 如果未设置该值,它将是null
。
Integer[][] board = new Integer[8][8];
...
if (board[x][y] != null) { ... }
回答by Kevin Bowersox
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
}
}
回答by OnResolve
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.
您可以创建一个方法,首先检查 x, y 是否在数组的边界内,如果是,则该值不为空。我不相信数组有内置方法,但有类似于 .contains() 的辅助函数用于 ArrayLists。
回答by TofuBeer
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).
不使用 int 可能更好,如果您真的必须将其作为 int 使用,则可以使用 Integer,但一般来说,复杂对象会更好(例如 ChessPiece 或其他东西)。这样您就可以检查该值是否为 == null(null 表示尚未设置)。
回答by Mike McMahon
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.
Java 没有 equiv。isset 因为知道某些东西是否真的被设置不仅仅是将一个值塞进一个位置。