jtan
jtan

Reputation: 129

2D Arrays and Generics Issue (Java)

I'm having an issue understanding some compiler-errors, regarding 2D arrays (ArrayList containing an ArrayList) and generics. My understanding of generics isn't the best, so I tried to research the issue beforehand and still ended up confused.

According to comments on 2D dynamic array using ArrayList in Java, you can't mix arrays with generics (or rather, you can with @SuppressWarnings("unchecked"), but are discouraged from doing so). However, I'm not sure what this exactly means.

Here is my problem code:

    blocks = new ArrayList<ArrayList<BarrierBlock>>(columns); // initialize rows
    for (int i = 0; i < columns; i++){
        // blocks.get(i) = new ArrayList<BarrierBlock>(rows);  <- ERROR = (unexpected type; required: variable, found: value)
        blocks.add(new ArrayList<BarrierBlock>(rows)); // initialize columns
    }

    // initilize each block
    for (int i = 0; i < blocks.size(); i++){
        for (int j = 0; i < blocks.get(i).size(); j++){
            int[] blockLoc = {location[0] + (i*BLOCK_SIDE_LENGTH), location[1] + (j*BLOCK_SIDE_LENGTH)};
            // blocks.get(i).get(j) = new BarrierBlock(BLOCK_SIDE_LENGTH, blockLoc); <- ERROR = (unexpected type; required: variable, found: value)
            blocks.get(i).add( new BarrierBlock(BLOCK_SIDE_LENGTH, blockLoc)); // initialize 2D array elements
        }
    }

The two lines that I commented out were my initial attempts at initializing the arrays. The compiler complained when I tried this and gave me the error listed. What does this error mean? I would think that both sides are of the declaration statement are variables.

After looking around, I found out that I'm supposed to use the add(E e) method of ArrayList. But what is the main difference? In the new way I'm initializing arrays, doesn't that also "mix arrays with generics"?

Upvotes: 2

Views: 575

Answers (1)

Jean-Bernard Pellerin
Jean-Bernard Pellerin

Reputation: 12670

Get RETURNS the object at the given index, it can't be used to SET the object.

here are things you CAN do with get:

list l = new list();
item a;
l.add(a);
item b = l.get(0);
b.property = 10;
l.get(0).property == 10; //true, a is the same object as b
b = new item();
l.get(0) == b; //false, list[0] is still a, b is now pointing to a different object
l.get(0) = b; //error, you can't assign to list.get

Upvotes: 1

Related Questions