Home Backend Development XML/RSS Tutorial Detailed introduction to the use of enumerations in java

Detailed introduction to the use of enumerations in java

Dec 19, 2016 pm 02:23 PM

Enumeration features

1. Using enum to define an enumeration class inherits the java.lang.Enum class by default instead of inheriting the Object class. Among them, the java.lang.Enum class implements two interfaces, java.lang.Serializable and java.lang.Comparable

2. The constructor of the enumeration class can only use the private access modifier, if the access control of its constructor is omitted symbol, the private modification is used by default;

3. All instances of the enumeration class must be explicitly listed in the enumeration class, otherwise this enumeration class will never be able to generate instances. When these instances are listed, the system automatically adds public static final modifications without the need for programmers to add them explicitly.

public enum Week {
    MON{
        public String toLocaleString(){
            return "星期一";
        }
    },TUES{
        public String toLocaleString(){
            return "星期二";
        }
    },WEB{
        public String toLocaleString(){
            return "星期三";
        }

    },THUR{
        public String toLocaleString(){
            return "星期四";
        }

    },FRI{
        public String toLocaleString(){
            return "星期五";
        }

    },SAT{
        public String toLocaleString(){
            return "星期六";
        }

    },SUN{
        public String toLocaleString(){
            return "星期日";
        }

    };
    public abstract String toLocaleString();
}
Copy after login

Traversal of enumerations

public class EnumTest {
    public static void main(String[] args){
        for(Week w:Week.values()){
            System.out.println(w);
        }
    }
}
Copy after login

Common methods of enumerations


int compareTo method

String name() returns the name of the enumeration instance

int ordinal() returns the enumeration value in the enumeration Index

String toString() returns the instance name of the enumeration which is more commonly used than name

public static valueOf()

public class EnumTest {
    public static void main(String[] args){
        Week day =Week.FRI;
        System.out.println(day);//FRI
        System.out.println(day.name());//FRI
        System.out.println(day.ordinal());//4
        System.out.println(Week.valueOf("SUN").toLocaleString());//星期日
        System.out.println(Week.values().length);//7  获取枚举长度
    }
}
Copy after login

Constructor of the enumeration

public enum Gender {
    MALE("男"),FEMALE("女");
    private String name;
    private Gender(String name){
        this.name =name;
    }
    public String getName(){
        return this.name;
    }
    public String toString(){
        String name = null;
        switch(this){
        case MALE:
            name="男";
            break;
        case FEMALE:
            name="女";
            break;
        }
        return name;
    }

}
Copy after login

Comprehensive application example of the enumeration: traffic light

Detailed introduction to the use of enumerations in java

public enum Lamp {
     /*每个枚举元素各表示一个方向的控制灯*/    
     S2N("N2S","S2W",false),S2W("N2E","E2W",false),E2W("W2E","E2S",false),E2S("W2N","S2N",false),
     /*下面元素表示与上面的元素的相反方向的灯,它们的“相反方向灯”和“下一个灯”应忽略不计!*/
     N2S(null,null,false),N2E(null,null,false),W2E(null,null,false),W2N(null,null,false),
     /*由南向东和由西向北等右拐弯的灯不受红绿灯的控制,所以,可以假想它们总是绿灯*/
     S2E(null,null,true),E2N(null,null,true),N2W(null,null,true),W2S(null,null,true);

     private Lamp(String opposite,String next,boolean lighted){
         this.opposite = opposite;
         this.next = next;
         this.lighted = lighted;
     }

 
     /*当前灯是否为绿*/    
     private boolean lighted;
     /*与当前灯同时为绿的对应方向*/    
     private String opposite;
     /*当前灯变红时下一个变绿的灯*/    
     private String next;
     public boolean isLighted(){
         return lighted;
     }

     /**
      * 某个灯变绿时,它对应方向的灯也要变绿
      */    
     public void light(){
         this.lighted = true;
         if(opposite != null){
             Lamp.valueOf(opposite).light();
         }
         System.out.println(name() + " lamp is green,下面总共应该有6个方向能看到汽车穿过!");

     }

     /**
      * 某个灯变红时,对应方向的灯也要变红,并且下一个方向的灯要变绿
      * @return 下一个要变绿的灯
      */    
     public Lamp blackOut(){
         this.lighted = false;
         if(opposite != null){
             Lamp.valueOf(opposite).blackOut();
         }        

         Lamp nextLamp= null;
         if(next != null){
             nextLamp = Lamp.valueOf(next);
             System.out.println("绿灯从" + name() + "-------->切换为" + next);            
             nextLamp.light();
         }
         return nextLamp;
     }
 }
Copy after login

The above is the detailed introduction to the use of enumerations in Java. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles