首次發佈時,對我正在處理的表類有疑問。出於某種原因,添加新行不會添加正確的行數。我添加了代碼Java表類結構
public void addRow(int i) {
if (i < 0 || i > rows()) throw new IndexOutOfBoundsException();
table.add(i, new ArrayList<T>());
for(int j = 0; j < cols(); j++) {
table.get(i).add(null);
}
}
public void addCol(int j) {
if (j < 0 || j > cols()) throw new IndexOutOfBoundsException();
if(rows() == 0) {
addRow(0);
}
for (int i = 0; i < rows(); i++) {
table.get(i).add(j, null);
}
}
這些是我必須在表格中添加新行和列的方法。以下是我用來測試的內容。出於某種原因,它增加了第五排。不知道從哪裏。
Table<Integer> table = new Table<>(Integer.class);
for(int i = 0; i < 4; i++) {
table.addCol(table.cols());
}
for(int i = 0; i < 4; i++) {
table.addRow(table.rows());
}
任何幫助或想法將不勝感激,謝謝!
全碼:
public class Table<T> implements AbstractTable<T> {
List<List<T>> table;
public Table(Class<T> t) { table = new ArrayList<>(); }
public int rows() { return table.size(); }
public int cols() {
if(rows() == 0) {
return 0;
} else {
return table.get(0).size();
}
}
public T get(int i, int j) {
if (i < 0 || i > rows() - 1 || j < 0 || j > cols()-1)
throw new IndexOutOfBoundsException();
return table.get(i).get(j);
}
public T set(int i, int j, T x) {
if (i < 0 || i > rows() - 1 || j < 0 || j > cols()-1)
throw new IndexOutOfBoundsException();
return table.get(i).set(j, x);
}
public void addRow(int i) {
if (i < 0 || i > rows()) throw new IndexOutOfBoundsException();
table.add(i, new ArrayList<T>());
for(int j = 0; j < cols(); j++) {
table.get(i).add(null);
}
}
public void addCol(int j) {
if (j < 0 || j > cols()) throw new IndexOutOfBoundsException();
if(rows() == 0) {
addRow(0);
}
for (int i = 0; i < rows(); i++) {
table.get(i).add(j, null);
}
}
public void removeRow(int i) {
if (i < 0 || i > rows() - 1) throw new IndexOutOfBoundsException();
table.remove(i);
}
public void removeCol(int j) {
if (j < 0 || j > cols() - 1) throw new IndexOutOfBoundsException();
for (int i = 0; i < rows(); i++) {
table.get(i).remove(j);
}
}
public static void main(String[] args) {
Table<Integer> table = new Table<>(Integer.class);
for(int i = 0; i < 4; i++) {
table.addCol(table.cols());
}
for(int i = 0; i < 4; i++) {
table.addRow(table.rows());
}
System.out.println("rows: " + table.rows() + "\ncols: " + table.cols());
table.removeCol(1);
table.removeRow(1);
System.out.println("rows: " + table.rows() + "\ncols: " + table.cols());
}
}
請分享你的'Table'類 – Joshua
或者在完整代碼至少[mcve]。 – shmosel
您是否調試過解決方案? –