Throsby
Throsby

Reputation: 199

Errors making an array of stacks

I'm working on a project in Java (I'm very new).

I'm trying to make two arrays that refer to the a similar set of objects (Indices 3-16) and respective 3 (Indices 0-2). I want the objects to be stacks (that I changed to be "Pile"s, which just have a method to report their lengths). Each of the "Pile" objects will be ready to accept "Piece" objects.

Pile<Piece>[] leftBoard = new Pile[16];
Pile<Piece>[] rightBoard = new Pile[16];
for (int i = 3; i < 16; i++){
    leftBoard[i] = new Pile<Piece>();
    rightBoard[i] = leftBoard[i];
}
for (int i = 0; i < 3; i++){
leftBoard[i] = new Pile<Piece>();
}
for (int i = 0; i < 3; i++){
    rightBoard[i] = new Pile<Piece>();
}

Please help! Thanks!

Upvotes: 1

Views: 99

Answers (1)

wchargin
wchargin

Reputation: 16047

Pile<Piece>[] is an array of generics. Due to type erasure in Java, this is a Very Bad Thing™. Instead, try something like this:

// Initialize arrays.
ArrayList<Pile<Piece>> leftBoard = new ArrayList<Pile<Piece>>(16);
ArrayList<Pile<Piece>> rightBoard = new ArrayList<Pile<Piece>>(16);

// Fill arrays so we can use the "set" method.
leftBoard.add(Collections.<Pile<Piece>>nCopies(null));
rightBoard.add(Collections.<Pile<Piece>>nCopies(null));

// Store values.
for (int i = 3; i < 16; i++){
    Pile<Piece> thisPiece = new Pile<Piece>();
    leftBoard.set(i, thisPiece);
    rightBoard.set(i, thisPiece);
}
for (int i = 0; i < 3; i++){
    leftBoard.set(i, new Pile<Piece>());
}
for (int i = 0; i < 3; i++){
     rightBoard.set(i, new Pile<Piece>());
}

ArrayList is also nicer because it's dynamically resizable (among many other things).

Quick rundown: if you have String[] array and `ArrayList list, then:

  • array[i] is the same as list.get(i)
  • array[i] = var is the same as list.set(i, var)
  • You can add elements to the end with list.add(var)
  • You can remove elements from anywhere with list.remove(index) or list.remove(var)
  • For more, see the ArrayList documentation or Java Tutorial on the subject.

EDIT: On the topic of unmodifiable lists:

List<MyObject> l = Collections.unmodifiableList(myList);
l.get(0);             // valid as long as element exists
l.get(0).foo();       // valid
l.get(0).setFoo(bar); // valid
l.remove(foo);        // INVALID
l.add(foo);           // INVALID

So you can manipulate the objects inside the list but can't modify their position in the list or the contents of the list itself. Imagine a prison on lockdown - nobody in or out, but you can still talk to the prisoners.

If you want the Piles to remain where they are but be able to move the Pieces, an unmodifiable list sounds good to me. As long as you have a method like somePile.setPiece(somePiece), this should work fine.

Upvotes: 1

Related Questions