【问题标题】:Using Java/Guava Optional<T> class to create and handle matrices of objects使用 Java/Guava Optional<T> 类创建和处理对象矩阵
【发布时间】:2013-02-01 12:26:52
【问题描述】:

我正在考虑使用 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();
    }
}

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

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

我认为我缺少关于这个 Optional 类的一些重要内容。

谢谢

【问题讨论】:

    标签: java multidimensional-array matrix guava


    【解决方案1】:

    我修正了你代码中的一些错误,并添加了 cmets 来解释:

    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”类。

    【讨论】:

    • 谢谢!,我将继续使用数组,因为像方括号索引一样...机会是有一天我将不得不返回并更新到表,但出于某种原因,一如既往,我喜欢相信我不会... :)
    猜你喜欢
    • 2020-07-14
    • 2014-10-24
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多