java-泛型和内部类
发布时间:2022-06-08 13:55:41 314
相关标签: # php
Cell类应该是静态的吗?如果类型参数不需要是静态的,是否可以从外部类共享?
如有任何澄清,将不胜感激。
public class Matrix {
private final int numberOfRows;
private final int numberOfColumns;
private final List<Cell> data;
public Matrix(int numberOfRows, int numberOfColumns) {
this.numberOfRows = numberOfRows;
this.numberOfColumns = numberOfColumns;
data = buildMatrix();
}
private List<Cell> buildMatrix() {
return IntStream.range(0, numberOfRows * numberOfColumns)
.mapToObj(i -> new Cell(i / numberOfColumns, i % numberOfColumns))
.collect(Collectors.toUnmodifiableList());
}
public int getNumberOfRows() {
return numberOfRows;
}
public int getNumberOfColumns() {
return numberOfColumns;
}
public Cell get(int rowId, int columnId) {
return get(rowId, columnId, cell -> cell.rowId == rowId && cell.columnId == columnId).get(0);
}
public List<Cell> getRow(int rowId) {
return get(rowId, 0, cell -> cell.rowId == rowId);
}
public List<Cell> getColumn(int columnId) {
return get(0, columnId, cell -> cell.columnId == columnId);
}
public List<Cell> getAscendingDiagonal(int rowId, int columnId) {
return get(rowId, columnId, cell -> cell.rowId - rowId == cell.columnId - columnId);
}
public List<Cell> getDescendingDiagonal(int rowId, int columnId) {
return get(rowId, columnId, cell -> cell.rowId - rowId == -(cell.columnId - columnId));
}
private List<Cell> get(int rowId, int columnId, Predicate<Cell> filter) {
return data.stream()
.filter(filter)
.sequential()
.collect(Collectors.toUnmodifiableList());
}
public void occupyCell(int rowId, int columnId, T t) {
get(rowId, columnId).setOccupant(t);
}
public void reset() {
data.forEach(Cell::clear);
}
static class Cell {
private final int rowId;
private final int columnId;
private T occupant;
private Cell(int rowId, int columnId) {
this.rowId = rowId;
this.columnId = columnId;
}
public Optional getOccupant() {
return Optional.ofNullable(occupant);
}
public int getRowId() {
return rowId;
}
public int getColumnId() {
return columnId;
}
private void setOccupant(T t) {
occupant = t;
}
private void clear() {
occupant = null;
}
@Override
public String toString() {
return "Cell{" +
"rowId=" + rowId +
", columnId=" + columnId +
", occupant=" + occupant +
'}';
}
}
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报