我试图检查一个二维数组是否包含一个对象,你会怎么做?
答案 0 :(得分:2)
您必须使用嵌套循环。假设您有一个Integer
数组的数组,并且您想要检查数组中是否有特定的数字:
static boolean contains(Integer[][] array, Integer wantedInt) {
// For each sub-array
for (int i = 0; i < array.length; i++) {
// For each element in the sub-array
for (int j = 0; j < array[i].length; j++) {
// If the element is the wanted one
if (array[i][j].equals(wantedInt)) {
// We've found it
return true;
}
}
}
// We didn't find the wanted number
return false;
}
您可以使用相同的逻辑通过使用泛型来搜索任何对象类型:
static <T> boolean contains(T[][] array, T wantedObj) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j].equals(wantedObj)) {
return true;
}
}
}
return false;
}
答案 1 :(得分:0)
Object objects[][] = new Object[100][];
Object objectToLocate = null;
outerloop:
for (Object[] object : objects) {
for (Object o : objects) {
if (o == objectToLocate) {
System.out.println("Found it!");
break outerloop;
}
}
}
答案 2 :(得分:0)
以下是对象的解决方案:
Object[][] twoDArray = new Object[x][y];
// Fill array
for (int i = 0; i < twoDArray.length; ++i)
{
for (int j = 0; j < twoDArray[i].length; ++j)
{
if (twoDArray[i][j].equals(someObject))
{
// do something
}
}
}