【问题标题】:How to use enum? java [duplicate]如何使用枚举? java [重复]
【发布时间】:2015-02-06 02:23:58
【问题描述】:

我听说过枚举类型,我在网上查了一下,但我找不到一个很好的解释,说明它比使用常量更好。如果我们想应用它,谁能解释它比使用常量更好以及如何在下面的代码中使用它:

(让我们用它来定义我的扑克牌类中的以下数据: - enum Suit {HEARTS, DIAMONDS, SPADES, CLUBS} - enum Face {ACE, JACK, QUEEN, KING}

public class Card {

    final static int MAX_SUITS = 4;
    final static int MAX_FACE_VALUES = 13;

    private int suit;
    private int faceValue;

    public Card(int faceValue, int suit) {
        this.suit = suit;
        this.faceValue = faceValue;
    }

    public int getSuit() {
        return suit;
    }

    public int getFaceValue() {
        return faceValue;
    }
    public void setSuit(int suit) {
        this.suit = suit;
    }

    public void setFaceValue(int faceValue) {
        this.faceValue = faceValue;
    }

    public String convertSuitToString() {
        if (this.suit >= 1 && this.suit <= 4) {
            if (this.suit == 1)
                return "HEARTS";
            else if (this.suit == 2)
                return "DIAMONDS";
            else if (this.suit == 3)
                return "SPADES";
            else if (this.suit == 4)
                return "CLUB";
        }
        return "((Invalid Suit Entry))";
    }

    public String convertFaceToString() {
        if (this.faceValue >= 1 && this.faceValue <= 13) {
            if (this.faceValue == 1)
                return "ACE";
            else if (this.faceValue >= 2 && this.faceValue <= 10)
                return this.faceValue + "";
            else if (this.faceValue == 11)
                return "JACK";
            else if (this.faceValue == 12)
                return "QUEEN";
            else if (this.faceValue == 13)
                return "KING";
        }
        return "((Invalid Face Value Entry))";
    }

    public String toString() {
        return "You got " + convertFaceToString() + " of " + convertSuitToString();
    }
}

【问题讨论】:

  • 常量通常是未定义且难以控制的,枚举使您可以更严格地控​​制可接受的值和类或方法可能期望的值,而不是使用 int
  • EnumsConstants 不是一回事......你的问题听起来像是一个是另一个的补充;他们不一定是那样。 constant 有一个值,即常量enumeration 可以有多个值,您可以根据需要分配。
  • “它如何比使用常量更好” the official tutorial 对此进行了解释。
  • 简单地说:它们是类型安全的,并且在 Java 场景中,它们可以通过行为(和成员)来丰富。
  • 我希望能得到帮助,而不是得到不确定的判断。我选择在 Stack Overflow 中分享我的问题,以获得知道如何提供帮助的人的帮助,而不是通过聪明的侦探成员。毕竟,我们都是这里的一员,都在追求同一个目标。从我们的错误中学习。如果我愿意作弊或不管这些人怎么想,我可以用许多不同的方式来作弊。所以,请尝试帮助,或者不要成为寻求帮助的人的障碍!

标签: java enums constants


【解决方案1】:

谁能解释一下它比使用常量更好吗?

一个并不比另一个更好,只是不同。以下是enum 的一些优点。


枚举

  • 可以在switch语句中使用
  • 提供有用的方法,见documentation
  • 可以表示为一个充满constantsclass
  • 类型安全,使用constants,您可以使用unallowed 值,而enum 强制您使用它的属性。
  • EnumSetEnumMap 课程

例子:

//Supported color constants
public static final int RED = 1;
public static final int BLUE = 2;

setColor(3);//would compile, but would fail later.

虽然enum 会迫使你接受它的价值。

【讨论】:

  • @askd 这个答案是否帮助您了解更多?
猜你喜欢
  • 2018-10-21
  • 2019-10-09
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多