我正在尝试使用values方法来查找枚举类型的给定值。出于某种原因,它说我必须创建一个values()方法,但这应该是一个内置方法(至少我是这么认为的)。以下是我遇到问题的代码:
public class Suit {
public enum SUIT{
CLUBS("Clubs"), HEARTS("Hearts"), SPADES("Spades"), DIAMONDS("Diamonds");
private String suitType;
SUIT(String suitType){
this.suitType = suitType;
}
public String getSuit(){
return suitType;
}
}
}
public class Rank {
private static int ACEVal;
public void setACEVal(int ACEVal){
this.ACEVal = ACEVal;
}
public int getACEVal(){
return ACEVal;
}
public enum RANK{
ACE(14, "Ace"),
TWO(2, "Two"),
THREE(3, "Three"),
FOUR(4, "Four"),
FIVE(5, "Five"),
SIX(6, "Six"),
SEVEN(7, "Seven"),
EIGHT(8, "Eight"),
NINE(9, "Nine"),
TEN(10, "Ten"),
JACK(10, "Jack"),
QUEEN(10, "Queen"),
KING(10, "King");
public int rankVal;
String cardType;
RANK(int rankValue, String cardType){
rankVal = rankValue;
this.cardType = cardType;
}
public int getRankVal(){
return rankVal;
}
public String getCardType(){
return cardType;
}
}
}
public class CreateDeck {
ArrayList<CreateCard> DeckArray = new ArrayList<CreateCard>(); //uses the cards that were created in CreateCard to load into the ArrayList
public void createDeck(){
for(int i = 0; i < 13; i++){ //loops thirteen times for each different type of card (Ace, Two, Three, etc...){
Rank rankNum = Rank.values()[i]; //gets the type of rank
for(int j = 0; j < 4; j++){ //loops for the four different suits (Clubs, Spades, Hearts, Diamonds)
CreateCard card = new CreateCard(rankNum, Suit.values()[j]);
DeckArray.add(card); //adds the created card to the deck
}
}
为什么我无法使用.values()?
答案 0 :(得分:0)
编译器添加了values()方法。它是静态的并返回枚举常量的数组。
public static E [] values();
您可以迭代值而不是使用索引。注意你的名字,你提供的枚举是大写的!
for(RANK rank : RANK.values()) { ... }
for(SUIT suit : SUIT.values()) { ... }
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Enum是所有Java语言枚举类型的通用基类。有关枚举的更多信息,包括编译器合成的隐式声明方法的描述,可以在Java™语言规范的第8.9节中找到。
http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html
关键字枚举只是扩展Enum&lt;&gt;的简短方法。这就是为什么你不能从另一个类扩展枚举的原因:Java中的单继承。