【问题标题】:get 2d generic matrix iterator获取二维通用矩阵迭代器
【发布时间】:2018-03-28 10:49:37
【问题描述】:

我正在尝试制作一个可以容纳不同对象的二维矩阵,主要是 int 和 String。到目前为止,我已经设法正确存储值(以某种方式),但我不知道如何从包含 T 值的 2d 矩阵中生成迭代器,因此它可以在下面的 test2 方法中使用。

public class Matrix<T> implements Iterable<T>  {

    private T[][] matrix;

    public Matrix(int rows, int columns) {

    this.rows = rows;
    this.columns = columns;

    matrix = (T[][]) new String[rows][columns];
    }

    public void insert(int row, int column, T value) {
    matrix[row][column] = (T) value;        
    }
    public Iterator<T> iterator() {

    ArrayList<ArrayList<String>> matrixList = new ArrayList<ArrayList<String>>();

    ArrayList<?> a = new ArrayList<>(Arrays.asList(matrix[0][0]));

        return (Iterator<T>) (a.iterator());
    }
}

假设是test2方法中这个测试的答案:

    @Test
    public void test2() {
        Matrix<String> m = new Matrix<String>(2, 2);

        m.insert(0, 0, "a");
        m.insert(0, 1, "b");
        m.insert(1, 0, "c");
        m.insert(1, 1, "d");

    for (String element : m) {
        System.out.println(element);
    }
}

到目前为止,它只打印我选择的矩阵中的值(在本例中为“a”)。我想让它打印矩阵中的所有值。 如果我

ArrayList a = new ArrayList(Arrays.asList(matrix)); 它说: lJava.lang.String 不能转换为 Java.lang.String。

要温柔,但要诚实,我是菜鸟

【问题讨论】:

    标签: java generics matrix iterator


    【解决方案1】:

    您只在 Iterator 的 0,0 索引上添加元素。像这样重写你Iterator

    public Iterator<T> iterator() {
    
        ArrayList<T> a = new ArrayList<>();
        for (int i = 0; i < rows; i++) {
            Collections.addAll(a, matrix[i]);
        }
        return (Iterator<T>) (a.iterator());
    }
    

    它应该可以工作。

    【讨论】:

    • 天啊,我已经尝试了几个小时来解决这个问题..为什么我不能得到这个?!非常感谢你!
    猜你喜欢
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2017-06-28
    • 2012-06-20
    • 2014-03-26
    • 1970-01-01
    相关资源
    最近更新 更多