Question

I need to use a LinkedList to add cells of a prison with the cell numbers 1.1, 1.2, 1.3, 1.4 etc. There are two levels and odd numbered cells have 1 bunk whereas even numbered cells have 2 bunks. How can I do this?

I did this to create a linkedlist. That is in my Cells class and I have 2 child classes which inherit from the Cells class called Odd and Even for odd and even numbered cells. Do I place all the cells in the cell class or only odd in the odd class and even cells in the even class?

LinkedList<Cells> cellId = new LinkedList<Cells>();
public void add()
{}

I'm not sure what to put in the add method..

Was it helpful?

Solution

Following on from my comment above, here's an example of how you might implement it using arrays, assuming you have defined the constants LEVELS and CELLS_PER_LEVEL in your main class (i.e. using "private static final"):

Cell[][] cells = new Cell[LEVELS+1][];
for(int level = 1; level <= LEVELS; level++) {
    cells[level] = new Cell[CELLS_PER_LEVEL+1];
}

Of course, that leaves the cells themselves all as null. You'd need to initialize them as OddCell or EvenCell. For example, to create cell 1.5:

cells[1][5] = new OddCell();

Of course, arrays are actually numbered from zero, but because the cells are numbered from one it is simplest just to ignore these elements. cells[0] is left as null, because there is no "level 0". Likewise, cells[1][0] can be left as null, because there is no cell 1.0.

Arrays are a good choice if the number of cells never changes. On the other hand, if you have to add cells or even levels dynamically, then choose ArrayList instead. The syntax is not quite as friendly, though. For example, if you had a variable cells of type ArrayList<ArrayList<Cell>>, then to assign to cell 1.5 you would have to write:

cells.get(1).set(5, new OddCell());

Anyway, whether you use arrays, arraylists, or something else is ultimately your decision, and depends on the overall program.

OTHER TIPS

Having Odd and Even classes that are subclasses of Cell sounds very wrong to me. Rather, the Cell class should have a 'Number' property, and a method like isOdd() and/or isEven().

Regardless, I would say that all the cells should be in a single linked list.

You could do it like you want and just add the cells to the list (without extending the list). Something like:

public class Cell {
    // all the internal logic
}
public class EvenCell extends Cell {}
public class OddCell extends Cell {}

LinkedList<Cell> cells = new LinkedList<Cell>();
cells.add(new OddCell());
cells.add(new EvenCell());
// ...

Then later use something like instanceof to determine whether the cell is even or odd.

Cell c = cells.get(1);
if (c instanceof EvenCell) {
    // ...
} else {
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top