2015-04-04 24 views

回答

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; 
} 
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; 
      } 
     } 
    } 
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 
      } 
     } 
    }