java - 使用 Java/Guava Optional<T> 类创建和处理对象矩阵

标签 java multidimensional-array matrix guava

我正在考虑使用 Guava 库中的 Optional< 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. 如何指定“清空”一个单元格,使其不再包含引用?

我想我遗漏了关于这个 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 如何处理泛型没有很好的理解,则很难同时使用数组和泛型。使用集合通常是更好的方法。

总而言之,我会使用 Guava 的 Table 接口(interface)而不是您的“MatrixOfObjects”类。

关于java - 使用 Java/Guava Optional<T> 类创建和处理对象矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14646298/

相关文章:

java - 寻找数组中的最小值

java - Java SSL TrustManager 上的部分链验证

java如何找到二维数组中每一行的最大值

对二维结构体的指针感到困惑

python - 从数组创建矩阵

java - 网络不可靠和低带宽的 Java ORM 策略

java - Web 容器成功启动后如何调用 servlet 或 Controller 上的方法

java - 如果多维列表包含空列表,我可以确定它的维数吗?

python - 使用 openCV 和 python 旋转 2D 点

matlab - 在 MATLAB 中存储 16 × (2^20) 矩阵的最佳方法是什么?