I am considering using the Optional< T > class in Guava library to handle a matrix (2D grid) of objects, while avoiding the use of null references to denote empty cells.
I am doing something like:
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();
}
}
I have three questions about the code above:
- How to create an instance of the Array of Arrays of Optional?
- How to assign a MyObjectClass object to a cell (this should be correct I think)
- How to assign to “empty” a cell such that it does not contains a reference anymore?
I think I am missing something essential about this Optional class.
Thanks
I fixed a few errors in your code, and added comments to explain:
Here are a few alternatives to create a generic array: How to create a generic array in Java?
Note that it’s hard to use arrays and generics together if you don’t have a good understanding of how Java treats generics. Using collections is often a better approach.
All that said, I would use Guava’s Table interface instead of your “MatrixOfObjects” class.