Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList of abstract subclasses (must have different hashcode)

I am creating a game for a school project, and I have a 2 classes called Pieces and Powers, with subclasses Piece_Yellow, Piece_Blue ... and Power_Explode, Power_ChangeColor etc...

I was doing it with enum and someone from this website (mikera to be more precise) help me changing that and creating a better interaction with the pieces and the powers.

But now I have to change the old code, and I have problems with that because I was doing like this :

int x = 10, y = 5;
for (int i=0; i<10; i++) {
    if (pecas[x][y] == null)
        pecas[x][y] = new Piece(arrayPecas.get(rand.nextInt(arrayPecas.size())));
}

Like this my array was partially filled with 10 new pieces Objects with different colors (but no powers, that was the problem), and every single one had a different hashcode (for finding , comparing and deleting the pieces later)...

But Since we can't initiliaze an abstract class, the only solution that I've found to this problem was to do this :

int x = 10, y = 5;
for (int i=0; i<10; i++) {
    if (pecas[x][y] == null)
        pecas[x][y] = arrayPecas.get(rand.nextInt(arrayPecas.size()));
}

Like this the object is still added, but now I have 1 problems : 1 - All the hashcode from the pieces with the same color are the same... I don't really know how to solve this. I've read that I could override the hashcode method but there is no information to make the difference between them (and I can't store the position because I had to change it every time the piece change position).

like image 913
aliasbody Avatar asked Jun 04 '26 10:06

aliasbody


1 Answers

It doesn't seem that really the hashCodes that are your problem. It's that the objects are simply equal. Code that relies on two unequal objects having different hashCodes isn't strictly correct. return 1; is a perfectly legal implementation of Object#hashCode().

The simplest thing seems to be to put a clone() method on Piece that all the subclasses can implement in order to return copies in places where you want different, distinct, objects.

public abstract class Piece {

  public abstract Piece clonePiece();

}

public class YellowPiece extends Piece {

  @Override
  public Piece clonePiece() {
    return new YellowPiece(this.relevantThing1, this.relevantThing2 // etc etc)
  }
}

int x = 10, y = 5;
for (int i=0; i<10; i++) {
    if (pecas[x][y] == null)
        pecas[x][y] = arrayPecas.get(rand.nextInt(arrayPecas.size())).clonePiece();
}
like image 80
Affe Avatar answered Jun 07 '26 00:06

Affe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!