Since java does not have a generic array, I am using the regular trick of casting Object array to a type parameter. This is working fine when I have a formal type parameter like <T>
but not when I use bounded type parameter <T extends something>
.
Following Code using formal type works fine
public class Deck <T> {
private T [] cards;
private int size;
public Deck () {
cards = (T []) new Object[52];
size = 0;
}
}
public class BlackJackGame {
Deck<BlackJackCard> deck;
public BlackJackGame() {
deck = new Deck<>();
populate (deck);
deck.shuffle();
}
}
public class BlackJackCard extends Card {
}
Following code using bounded type throws error
public class Deck <T extends Card> {
private T [] cards;
private int size;
public Deck () {
cards = (T []) new Object[52];
size = 0;
}
}
public class BlackJackGame {
Deck<BlackJackCard> deck;
public BlackJackGame() {
deck = new Deck<>();
populate (deck);
deck.shuffle();
}
}
public class BlackJackCard extends Card {
}
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LCard;
at Deck.<init>(Deck.java:10)
at BlackJackGame.<init>(BlackJackGame.java:5)