2013-02-01 17 views
1

我正在考慮使用Guava庫中的可選< T>類來處理對象的矩陣(2D網格),同時避免使用空引用來表示空單元格。使用Java/Guava可選<T>類創建和處理對象的矩陣

我做這樣的事情:

class MatrixOfObjects() { 
    private Optional<MyObjectClass>[][] map_use; 

    public MatrixOfObjects(Integer nRows, Integer nCols) { 
     map_use = (Optional<MyObjectClass>[][]) new Optional[nRows][nCols]; 
     // IS THIS CAST THE ONLY WAY TO CRETE THE map_use INSTANCE? 
    } 

    public MyObjectClass getCellContents(Integer row, Integer col) { 
     return map_use[row][col].get(); 
    } 

    public void setCellContents(MyObjectClass e, Integer row, Integer col) { 
     return map_use[row][col].of(e); 
     // IS THIS THE CORRECT USE OF .OF METHOD? 
    } 

    public void emptyCellContents(Integer row, Integer col) { 
     map_use[row][col].set(Optional.absent()); 
     // BUT SET() METHOD DOES NOT EXIST.... 
    } 

    public Boolean isCellUsed(Integer row, Integer col) { 
     return map_use[row][col].isPresent(); 
    } 
} 

我對上面的代碼三個問題:

  1. 如何創建可選的數組的數組的一個實例?
  2. 如何將MyObjectClass對象分配給單元格(我認爲這應該是正確的)
  3. 如何將「空」分配給不包含引用的單元格?

我想我缺少一些關於這個可選類的重要內容。

感謝

回答

4

我固定在你的代碼的一些錯誤,並添加註釋來解釋:

class MatrixOfObjects { // class declaration should not have a "()" 
    private Optional<MyObjectClass>[][] map_use; 

    public MatrixOfObjects(Integer nRows, Integer nCols) { 
     map_use = (Optional<MyObjectClass>[][]) new Optional[nRows][nCols]; 
    } 

    public MyObjectClass getCellContents(Integer row, Integer col) { 
     return map_use[row][col].get(); 
    } 

    public void setCellContents(MyObjectClass e, Integer row, Integer col) { 
     // removed "return" keyword, since you don't return anything from this method 
     // used correct array assignement + Optional.of() to create the Optional 
     map_use[row][col] = Optional.of(e); 
    } 

    public void emptyCellContents(Integer row, Integer col) { 
     // unlike lists, arrays do not have a "set()" method. You have to use standard array assignment 
     map_use[row][col] = Optional.absent(); 
    } 

    public Boolean isCellUsed(Integer row, Integer col) { 
     return map_use[row][col].isPresent(); 
    } 
} 

這裏是創建一個通用的陣列的幾個備選方案:How to create a generic array in Java?

請注意,這是如果您對Java如何對待泛型沒有很好的理解,那麼很難一起使用數組和泛型。使用集合通常是更好的方法。

所有這一切說,我會用Guava的Table接口,而不是你的「MatrixOfObjects」類。

+0

謝謝! 我會繼續與陣列,因爲像方括號索引...機會是,我將不得不回到有一天,並更新到表,但由於某種原因,一如既往,我享受相信我不會...... :) –