我意识到toString方法添加了[],在这种情况下多个括号,即[[ value ]].
我需要删除括号,并转换为字符串格式,如此输出...
a b c
e f g
i h j
当前输出......
[[a], [b], [c]]
[[d], [e], [f]]
[[i], [h], [g]]
尝试:我有一个可迭代的方法,但不确定是否需要将其用于此目的?
private ArrayList<ArrayList<ArrayList<T>>> matrixOne;
public String toString() {
return matrixOne.toString().replace("[","").replace("]","");
}
更新此处是可用的可验证代码。获取此输出:
public class Matrix<T> implements Iterable {
private int rows;
private int columns;
private int value;
private ArrayList<ArrayList<ArrayList<T>>> matrixOne;
public Matrix(int rows, int columns) {
this.rows = rows;
this.columns = columns;
matrixOne = new ArrayList<ArrayList<ArrayList<T>>>();
// matrixOne = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < rows; i++) {
matrixOne.add(new ArrayList<ArrayList<T>>());
for(int j = 0; j < columns; j++) {
matrixOne.get(i).add(new ArrayList<T>());
}
}
}
public void insert(int row, int column, T value) {
matrixOne.get(row).get(column).add( value);
}
// THIS METHOD!
public String toString() {
return matrixOne.toString().replaceAll("\[\[|\]|,|\[|\]\]", "");
}
public Iterator iterator() {
Iterator itr = matrixOne.iterator();
return itr;
}
public static void main(String[] args) {
Matrix<String> nums = new Matrix(3, 3);
nums.insert(0, 0, "a");
nums.insert(0, 1, "b");
nums.insert(0, 2, "c");
//
nums.insert(1, 0, "d");
nums.insert(1, 1, "e");
nums.insert(1, 2, "f");
//
nums.insert(2, 2, "g");
nums.insert(2, 1, "h");
nums.insert(2, 0, "i");
for(Object nm : nums) {
System.out.println(nm.toString());
}
想法好吗?
答案 0 :(得分:1)
简单替换(...)对我有用:
public class Main
{
public static void main(String[] args) throws Exception
{
ArrayList<String> al1 = new ArrayList<String>();
al1.add("a");
al1.add("b");
ArrayList<String> al2 = new ArrayList<String>();
al2.add("1");
al2.add("2");
ArrayList<ArrayList<String>> al = new ArrayList<ArrayList<String>>();
al.add(al1);
al.add(al2);
System.out.println(al);
System.out.println( al.toString().replace("[", "").replace("]", "") );
}
}