我正在考虑使用 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();
}
}
我对上面的代码有三个问题:
- 如何创建可选数组的数组实例?
- 如何将 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 如何处理泛型没有很好的理解,则很难同时使用数组和泛型。使用集合通常是更好的方法。
总而言之,我会使用 Guava 的 Table 接口(interface)而不是您的“MatrixOfObjects”类。
关于java - 使用 Java/Guava Optional<T> 类创建和处理对象矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14646298/