How to fill a two Dimensional ArrayList in java with Integers?

前端 未结 8 2438
迷失自我
迷失自我 2020-12-15 01:57

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.

8条回答
  •  旧巷少年郎
    2020-12-15 02:25

    I'm not sure how to initialize such an array or store information.

    Like this for instance:

    List> twoDim = new ArrayList>();
    
    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));
    

    or like this if you prefer:

    List> twoDim = new ArrayList>() {{
        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());
    

    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> twoDim = new ArrayList>();
    
            String[] inputLines = { "0 1 0 1 0", "0 1 1 0 1", "0 0 0 1 0" };
    
            for (String line : inputLines) {
                List row = new ArrayList();
    
                Scanner s = new Scanner(line);
                while (s.hasNextInt())
                    row.add(s.nextInt());
    
                twoDim.add(row);
            }
        }
    }
    

提交回复
热议问题