如何用整数在java中填充二维ArrayList? [英] How to fill a two Dimensional ArrayList in java with Integers?

查看:26
本文介绍了如何用整数在java中填充二维ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个大小未知的二维数组.所以我决定使用 2d ArrayList 问题是我不确定如何初始化这样的数组或存储信息.

I have to create a 2d array with unknown size. So I have decided to go with a 2d ArrayList the problem is I'm not sure how to initialize such an array or store information.

假设我有以下数据

   0 connects 1
   2 connects 3 
   4 connects 5

.... 等高达大量的随机连接

....etc up to a vast amount of random connections

我想插入

true(1) into [0][1], 
true(1) into [2][3], 
true(1) into [4][5]. 

数组可以自动为我更新列/行吗

Can the array automatically update the column/rows for me

感谢任何帮助,谢谢

推荐答案

我不知道如何初始化这样的数组或存储信息.

例如:

List<List<Integer>> twoDim = new ArrayList<List<Integer>>();

twoDim.add(Arrays.asList(0, 1, 0, 1, 0));
twoDim.add(Arrays.asList(0, 1, 1, 0, 1));
twoDim.add(Arrays.asList(0, 0, 0, 1, 0));

或者喜欢这个:

List<List<Integer>> twoDim = new ArrayList<List<Integer>>() {{
    add(Arrays.asList(0, 1, 0, 1, 0));
    add(Arrays.asList(0, 1, 1, 0, 1));
    add(Arrays.asList(0, 0, 0, 1, 0));
}};

<小时>

要插入新行,请执行


To insert a new row, you do

twoDim.add(new ArrayList<Integer>());

并在您执行的特定上附加另一个元素

and to append another element on a specific row you do

twoDim.get(row).add(someValue);

<小时>

这是一个更完整的例子:


Here is a more complete example:

import java.util.*;

public class Test {

    public static void main(String[] args) {

        List<List<Integer>> twoDim = new ArrayList<List<Integer>>();

        String[] inputLines = { "0 1 0 1 0", "0 1 1 0 1", "0 0 0 1 0" };

        for (String line : inputLines) {
            List<Integer> row = new ArrayList<Integer>();

            Scanner s = new Scanner(line);
            while (s.hasNextInt())
                row.add(s.nextInt());

            twoDim.add(row);
        }
    }
}

这篇关于如何用整数在java中填充二维ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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