需要使用枚举

发布于 2024-11-06 08:12:40 字数 253 浏览 0 评论 0原文

我很清楚枚举在java中的高级使用。我也很清楚他们与普通课程的区别以及他们的需求的许多要点。

谁能给出一些带有高级枚举示例代码的实际示例?哪位可以清楚地阐述一下

我们应该避免上课的地方 应该使用枚举代替

请不要混淆。我不是问如何使用 enum 或者 enum 有什么用。对此有很多问题和答案。我正在寻找一些实时/现场/实际示例,我们应该避免任何其他数据类型或类。

I am clear with advanced use of enum in java. Many of the points which differentiate them from regular classes and tells their need are also clear to me.

Can anyone give some practical example with sample code for advanced enum? Which can clearly elaborate about

where we should avoid classes and
should use enum instead

.

Please dont be confused. I am not asking for how to use enum or what is the use of enum. There are many questions and answers on this. I am looking for some real time/ live / practical example where we should avoid any other data type or classes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

旧城空念 2024-11-13 08:12:40

使用常量时通常会使用枚举。它们的作用是为常量提供类型,而不是像在引入它们之前那样将它们“松散”为 intString

而不是说:

public static final int MALE = 1;
public static final int FEMALE = 2;

您可以说

  public enum Gender {
     MALE, FEMALE;
   } 

并引用它们为 Gender.MALEGender.FEMALE

如果没有枚举,setGender 的方法需要接受 int (在上面的示例中),并且我可以传递 1 或 2 以外的任何值。然后,其中的代码需要检查传递的 int 是否映射到常量等。在这种情况下,枚举提供了一种干净、简单的方法。

Enums are usually used when using constants. They act as providing a type for the constant, instead of leaving them 'loose' as ints or Strings like it was being done before they were introduced.

Instead of saying :

public static final int MALE = 1;
public static final int FEMALE = 2;

You can say

  public enum Gender {
     MALE, FEMALE;
   } 

and refer to them as Gender.MALE and Gender.FEMALE.

Without enums, the method to setGender needs to accept an int (in the above example) and I can pass anything other than 1 or 2. The code in there then needs to check if the int being passed maps to the constant, etc. Enums provide a clean and easy way in such situations.

好多鱼好多余 2024-11-13 08:12:40

您可以将其视为现实世界的示例

public class EnumExample
{
    public static  enum APP_STATUS{
        ALL_GOOD(1, "All things are going good"),
        WARNING(2, "SOMETHING IS BAD"),
        ERROR(3, "Its an Error"),
        FATAL(4, "Its crashed");

        private String  statusMessage;
        private int statusId;
        private APP_STATUS(int statusId, String statusMessage){
            this.statusId = statusId;
            this.statusMessage = statusMessage;
        }

        public int getStatusId(){
            return statusId;
        }

        public String getStatusMessage(){
            return statusMessage;
        }

        public boolean isAttentionRequired(){
            if(statusId<3)
                return false;
            else
                return true;
        }
    }

    public void handleAppStatusChange(APP_STATUS newStatus){
        if(newStatus.isAttentionRequired()){
            //notify admin
        }
        //Log newStatus.getStatusId() in the logfile
        //display newStatus.getStatusMessage() to the App Dash-Board
    }

    public void Test(){
        handleAppStatusChange(APP_STATUS.ALL_GOOD);
        handleAppStatusChange(APP_STATUS.WARNING);
        handleAppStatusChange(APP_STATUS.FATAL);
    }
}

- (我假设您了解枚举的所有基础知识..因此,我不会在这里解释它们)

you can consider this as a real-world example--

public class EnumExample
{
    public static  enum APP_STATUS{
        ALL_GOOD(1, "All things are going good"),
        WARNING(2, "SOMETHING IS BAD"),
        ERROR(3, "Its an Error"),
        FATAL(4, "Its crashed");

        private String  statusMessage;
        private int statusId;
        private APP_STATUS(int statusId, String statusMessage){
            this.statusId = statusId;
            this.statusMessage = statusMessage;
        }

        public int getStatusId(){
            return statusId;
        }

        public String getStatusMessage(){
            return statusMessage;
        }

        public boolean isAttentionRequired(){
            if(statusId<3)
                return false;
            else
                return true;
        }
    }

    public void handleAppStatusChange(APP_STATUS newStatus){
        if(newStatus.isAttentionRequired()){
            //notify admin
        }
        //Log newStatus.getStatusId() in the logfile
        //display newStatus.getStatusMessage() to the App Dash-Board
    }

    public void Test(){
        handleAppStatusChange(APP_STATUS.ALL_GOOD);
        handleAppStatusChange(APP_STATUS.WARNING);
        handleAppStatusChange(APP_STATUS.FATAL);
    }
}

(I am assuming that you know all the basics of enum.. and so, I am not explaining them here)

无言温柔 2024-11-13 08:12:40

尝试这个示例

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

用法:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY: System.out.println("Mondays are bad.");
                         break;

            case FRIDAY: System.out.println("Fridays are better.");
                         break;

            case SATURDAY:
            case SUNDAY: System.out.println("Weekends are best.");
                         break;

            default:     System.out.println("Midweek days are so-so.");
                         break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();          

    }
}

Try this example:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

Usage:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY: System.out.println("Mondays are bad.");
                         break;

            case FRIDAY: System.out.println("Fridays are better.");
                         break;

            case SATURDAY:
            case SUNDAY: System.out.println("Weekends are best.");
                         break;

            default:     System.out.println("Midweek days are so-so.");
                         break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();          

    }
}
流年已逝 2024-11-13 08:12:40

您应该查看 第 6 章枚举和注释(也许是 Java 枚举的最佳实践) 《nofollow noreferrer》Effective Java(第 2 版),本书的作者(Joshua Bloch)也是JDK 的 EnumEnumSet, EnumMap

或者您可以查看约书亚·布洛赫 (Joshua Bloch) 的会议,其中之一:
- Google I/O 2008 - 重新加载有效的 Java
- 有效的 Java - 这些年来仍然有效

You should look at Chapter 6 Enums and Annotations (maybe best practices for Java Enum) of Effective Java (2nd Edition), the author (Joshua Bloch) of this book is also author of JDK's Enum, EnumSet, EnumMap.

Or you can look at conference of Joshua Bloch, either one :
- Google I/O 2008 - Effective Java Reloaded
- Effective Java - Still Effective After All These Years

吐个泡泡 2024-11-13 08:12:40

请查看此内容以及一些

带有构造函数的附加枚举

enum enumConstr {
HUGE(10), OVERWHELMING(16), BIG(10,"PONDS");//(;)Compulsory

int ounces; String name;
enumConstr(int ounces){ this.ounces = ounces; }

enumConstr(int ounces,String name){
    this.ounces = ounces;
    this.name = name;
}

public int getOunces(){  return ounces; }
public String getName(){ return name; }
}//Enum completes

public class EnumWithConstr {
enumConstr size;

public static void main(String[] args) {
    EnumWithConstr constr = new EnumWithConstr();
    constr.size = enumConstr.BIG;

    EnumWithConstr constr1 = new EnumWithConstr();
    constr1.size = enumConstr.OVERWHELMING;

    System.out.println(constr.size.getOunces());//8
    System.out.println(constr1.size.getOunces());//16
    System.out.println(constr.size.getName());//PONDS
    System.out.println(constr1.size.getName());//null
}

}

 您永远不能直接调用枚举构造函数。枚举构造函数会自动调用,并使用您在常量值之后定义的参数。

 您可以为构造函数定义多个参数,并且可以重载枚举构造函数,就像重载普通类构造函数一样。

Check out this as well some additional

Enums with constructors

enum enumConstr {
HUGE(10), OVERWHELMING(16), BIG(10,"PONDS");//(;)Compulsory

int ounces; String name;
enumConstr(int ounces){ this.ounces = ounces; }

enumConstr(int ounces,String name){
    this.ounces = ounces;
    this.name = name;
}

public int getOunces(){  return ounces; }
public String getName(){ return name; }
}//Enum completes

public class EnumWithConstr {
enumConstr size;

public static void main(String[] args) {
    EnumWithConstr constr = new EnumWithConstr();
    constr.size = enumConstr.BIG;

    EnumWithConstr constr1 = new EnumWithConstr();
    constr1.size = enumConstr.OVERWHELMING;

    System.out.println(constr.size.getOunces());//8
    System.out.println(constr1.size.getOunces());//16
    System.out.println(constr.size.getName());//PONDS
    System.out.println(constr1.size.getName());//null
}

}

 You can NEVER invoke an enum constructor directly. The enum constructor is invoked automatically, with the arguments you define after the constant value.

 You can define more than one argument to the constructor, and you can overload the enum constructors, just as you can overload a normal class constructor.

日裸衫吸 2024-11-13 08:12:40

应该优先使用enum而不是class的最简单示例是单例

enum Singleton {
   INSTANCE
}

实例是延迟加载且线程安全的,因为类是延迟加载的并且它们的初始化是线程安全的。

这比使用常规类要简单得多。


对于实用程序类,我很好地使用了枚举,但这并不常见。

enum Utility {;
   public static returnType utilityMethod(args) { ... }
}

The simplest example of where an enum should used in preference to a class is a singleton

enum Singleton {
   INSTANCE
}

The instances is lazily loaded and thread safe because classes are lazily loaded and their initialisation is thread safe.

This is far simpler than using a regular class.


For a utility class I use an enum well, but this is not so common.

enum Utility {;
   public static returnType utilityMethod(args) { ... }
}
神妖 2024-11-13 08:12:40

当您知道值是明确定义的、在编译时已知的固定值集时。

您可以非常轻松地将枚举用作集合(使用 EnumSet),它允许您定义行为、按名称引用元素、打开它们等。

When you know values are well-defined, fixed set of values which are known at compile-time.

You can use an enum as a set very easily (with EnumSet) and it allows you to define behaviour, reference the elements by name, switch on them etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文