user22205
user22205

Reputation: 25

Java ArrayLists: Adding parent class and sub class to the same arraylist, solutions

I'm currently working on an independent project of writing a chess game. The issue I'm currently facing is I have a method that returns an arraylist of type Move (self explanatory) which is called when determining all of the legal moves. While this works fine, I introduced a class called Castle, which extends Move (I did this because unlike a normal move, castling affects 4 squares and not just 2).

I'd like the method getMoves() to be self contained, or be able to return all of the valid moves including objects of type Move and its child Castle.

The issue is if I include a declaration which adds valid castling moves to the method getMoves (which returns an array list of type move) I can either a.) add the arraylist as a type move, in which information is lost, or b.) a type castle, which changes the return arraylist to a type of all castle and obviously breaks the method.

Is there any graceful way to accomplish this? I'm looking for ways to solve this problem without re-writing the move class while keeping the getMoves method stand alone.

Upvotes: 0

Views: 804

Answers (3)

Hesham Attia
Hesham Attia

Reputation: 977

It's hard to make a good design decision without seeing how everything is used, but here are a couple of solutions you could consider:

  1. Make a Move superclass of both BasicMove and Castling, then make your method return a list of that Move superclass. In this case your current Move class should be renamed to BasicMove.

  2. Add a Castling as a field inside the Move class. You could save the rook's move inside the Move class, and the king's move inside the new Castling field.

Upvotes: 0

ABHIJITH GM
ABHIJITH GM

Reputation: 134

You can use arraylist of move objects and check for castle object using instanceof operator. Then caste the object to castle type.

if( moveobject instanceof Castle){
Castle castleobject = (Castle) moveobject;

// Do whatever u want to do with castleobject

}

Upvotes: 1

Nam Dam
Nam Dam

Reputation: 99

Another option is that you can use generic here. In your case, you want to return a list of either Move or Castle, or in global mean, a list of either Move or its sub-type. Below is example code:

public <T extends Move> List<T> getMoves();

With this way, if you need to add another sub-type of Move other than Castle, you do not need to modify the return type any more.

Upvotes: 0

Related Questions