我正在考虑使用Guava库中的Optional 类来处理对象的矩阵(2D网格),同时避免使用空引用来表示空单元格。

我正在做类似的事情:

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


我对上面的代码有三个问题:


如何创建可选数组的实例?
如何将MyObjectClass对象分配给单元格(我认为应该是正确的)
如何为“空”分配一个单元格,使其不再包含引用?


我想我缺少关于此Optional类的一些重要内容。

谢谢

最佳答案

我修复了您的代码中的一些错误,并添加了注释以解释:

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如何对待泛型,则很难将数组和泛型一起使用。使用集合通常是更好的方法。

所有这些,我将使用番石榴的Table接口而不是您的“ MatrixOfObjects”类。

09-10 01:28
查看更多