GwadaKing GwadaKing - 2 months ago 8
Java Question

Coord ArrayLists should both have the same size

In a bomberman-like puzzle game, those lines are made to identify the best spot to drop a bomb(between two crates). It's a 13*11 grid.

When I check the size of the 2 objects, the one stocking the X is far bigger than the other one.
They are supposed to have both the same size each coord X coming with his Y.

Being that first best moves are on the same Y axis, I suspect the 2nd arraylist not to create a new room to store them (but it is ArrayList and not Set so ?).

ArrayList<Integer> bestSpotX=new ArrayList<Integer>();
ArrayList<Integer> bestSpotY=new ArrayList<Integer>();
// ...
for (int line=0, col=0;line<11 && col<13;line++, col++) {
if ((map[line].charAt(col)=='0')&&(map[line+2].charAt(col)=='0')) {
bestSpotX.add(col);
bestSpotY.add(line+1);
}
}


Is my iteration false, or is it the way I'm adding the coord values ?

Answer

Why:

ArrayList<Integer> bestSpotX=new ArrayList<Integer>();    
ArrayList<Integer> bestSpotY=new ArrayList<Integer>();

and not:

class LineColLocation {
  protected int line, col;

// constructors, setters and getters
}

ArrayList<LineColLocation> bestSpots=new ArrayList<LineColLocation>();    


int bestSpotLine=...; // ... whatever logic to ...
int bestSpotCol=...;  // determine a *best spot*

LineColLocation bestSpot=new LineColLocation(bestSpotLine, bestSpotCol);
bestSpots.add(bestSpot);

This way you won't be able to accidentally mess with the **implicit requirement* of same number of X and Y in two different lists - you just materialize this constraint (make it explicit), make unnecessary the verification of this constraint and you'll be sure every time you can't screw the things.