使用ArrayLists创建矩阵 [英] Creating a Matrix with ArrayLists

查看:79
本文介绍了使用ArrayLists创建矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想创建一个具有n行和m列的ArrayList矩阵

I want to create an ArrayList-matrix with n-rows and m-columns, for example

   1 2 3 4 5

   1 2 3 4 5 

   1 2 3 4 5

   1 2 3 4 5

   1 2 3 4 5

我已经编写了创建这种矩阵的代码,但是当我清除包含列数据的列表时,我的代码没有显示值.这是我的

I've already written a code for creating such a matrix but my code doesn't display the values when I clear the list containing the column-data. Here is my

package testproject;

import java.util.ArrayList;

public class TestProject {

    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList<>();
        ArrayList<ArrayList<Integer>> mainList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            for (int k = 0; k < 5; k++) {
                intList.add(k);
            }
            mainList.add(intList);
            intList.clear(); //this line is probably the problem
        }
        for (int row = 0; row < mainList.size(); row++) {
            for (int col = 0; col < mainList.get(0).size(); col++) {
                System.out.print(mainList.get(row).get(col) + ",");
            }
            System.out.println("");
        }
    }
}

是否有可能清除 intList 的内容而不清除 mainList的内容?

Is there any possibility to clear the contents of intList without clearing the contents of mainList??

推荐答案

调用mainList.add(intList);时,您将指向intList对象的引用添加到mainList中,而不是复制值.您将必须每行创建一个"intList"实例,并且不清除任何内容.

When calling mainList.add(intList); you are adding a reference pointing to the intList object into your mainList rather than copying the values. You will have to create one instance of "intList" per row, and not clear anything.

这篇关于使用ArrayLists创建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆