Zodiac Zubeda Zodiac Zubeda - 1 year ago 168
Java Question

Java equivalent to python array initialization

What is the equivalent in Java to this in Python?

array_name = [0 for i in range(5)]

Specifically, I want to create a 2 dimensional Java ArrayList and initialize each value as 0. This is what I was thinking, in semi-psuedocode, following Python, but it obviously doesn't work:

ArrayList<ArrayList<Integer>> grid = new ArrayList<ArrayList<Integer>>() {{
(add(Arrays.asList(0 for i : ROWS) for j : COLUMNS);

Where ROWS and COLUMNS are constants defined elsewhere. In the end, I want a 2D ArrayList, with sizes given by the ROWS and COLUMNS constants, and each value initialized as 0. Is there a way to do this?

And ArrayLists don't allow primitive types as the generic type (like the primitive int). Then having the reference type doesn't have a default of 0 since it is an object. So any other questions concerning the initialization of an array to 0 that have to do with the primitive int don't answer mine.

Answer Source

To initialize a ArrayList with zeros could make use of the method nCopies

    int ROWS =3;
    int COLUMNS=3;
    List<List<Integer>> twoDimArray = new ArrayList<List<Integer>>();//declaration
    for (int i = 0; i < ROWS ; i++) { // cant rows 
        twoDimArray.add(Collections.nCopies(COLUMNS, new Integer(0)));
        //initialized to zero the number of columns you want

    /* Print  */

    for (List<Integer> list : twoDimArray) {

In the example use the List <> to replace ArrayList as it is much better ... and for references to this review Type List vs type ArrayList in Java

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download