Scenario:
I want to have an enum containing all the playing cards in a standard deck. For this example ignore the jokers.
Writing
enum Cards {
SPADE_1(0, 1),
SPADE_2(0, 2),
etc.
feels wrong.
I’d like to be able to do something like this
enum Card {
for (int suit=0; suit<4; suit++) {
for (int face=1; face<13; face++) {
new Card(suit, face);
}
}
}
I’ve considered defining card as a class containing suit and face fields, where suit and face are themselves enums. However in other scenarios (such as jokers having the suits red and black) this would allow for invalid card objects to be created (ie a joker of diamonds, or a red 10).
Self-answer:
Apparently I don’t have enough rep to post an answer to my own question.
I'm not sure if it's considered good form to answer my own question, but @Paul just gave me a brainwave.
Declare Card to have a private constructor, and use a
static Card getCard(suit, face)
method to validate combinations before returning them.
I don’t think it can be done using
enumbut we canimplementclassasenum. you can do something like below.Implementations:
EDIT:
set the
counterof the card. Earlier it would throwNullPointerExceptionfor index more than 15.USAGES:
OUTPUT: