Home >Java >javaTutorial >Java basic induction enumeration

Java basic induction enumeration

WBOY
WBOYforward
2022-05-26 11:50:332336browse

This article brings you relevant knowledge about java, which mainly introduces issues related to enumeration, including the basic operations of enumeration, the support of enumeration by collection classes, etc. Let’s take a look at the content below, I hope it will be helpful to everyone.

Java basic induction enumeration

Recommended study: "java Video Tutorial"

Enumeration is to allow the access to variables of a certain type The value can only be one of several fixed values, otherwise the compiler will report an error. Enumeration allows the compiler to control the illegal values ​​assigned by the source program during compilation. This cannot be achieved during the development stage by using ordinary variables. One goal.
After JDK1.5, use the keyword enum to define a new type, called the enumeration type
Enumeration (enum) and class (class), interface ( interface) are at the same level

Case introduction

Define a color, and only three colors, red, green and blue, can be defined

Normal method
Java basic induction enumeration
So how to solve this problem so that color can only choose one of the three colors? ? ?

Enum class and enum keyword

The enumeration class defined using the enum keyword is actually equivalent to defining a class, and this class inherits Class Enum class only.

public enum Color {
    RED,
    GREEN,
    BLUE;}

Java basic induction enumeration

Commonly used enumeration methods

##protected Enum(String name,int ordinal)This construction The method cannot be called directly from the outside and can only be accessed by its subclasses. This constructor is automatically called
public final String name()Returns the name of the enumeration
public String toString ()Returns the name of the enumeration
public final int ordinal()Returns the serial number of the enumeration, starting from 0 by default
public final boolean equals(Object other)Judge whether two enumerations are the same

Code

public class EnumTest {
    public static void main(String[] args) {
        //定义一个color变量,只能设置为RED、GREEN、BLUE
        Color color = Color.BLUE;
        System.out.println(color);
        System.out.println(color.name());
        System.out.println(color.toString());//三种方式都是打印名字
        System.out.println(color.ordinal());//返回枚举的序号RED--0、GREEN--1、BLUE--2

        Color[] values = Color.values();//返回所有枚举类型
        System.out.println(Arrays.toString(values));
    }}

Java basic induction enumeration

Basic operations of enumerations

Enumeration with constructor

The essence of an enumeration is a subclass that inherits the Enum class. The JVM compiler compiles the enumeration and generates a

final class

Enumerations are not allowed to be called from the outside, so they can only be privately modified
Java basic induction enumeration
The constructor can only be called in the object
Java basic induction enumeration

public enum Color {
    RED(10),
    GREEN(20),
    BLUE;
    private int Number;//属性

    private Color() {//默认构造方法
        System.out.println("无参构造器被调用了!!!");
    }

    private Color(int Number) {
        this.Number = Number;
        System.out.println("有参构造器被调用了!!!");
    }
    
    public int getNumber(){
        return Number;
	}}

Main method

public class EnumTest {
    public static void main(String[] args) {
        Color color = Color.RED;
        System.out.println(color.name());
        System.out.println(color.getNumber());//获取Number的值
    }}

Java basic induction enumeration

Enumeration implementation interface

In an enumeration type, you can inherit the interface. There are two ways to implement the interface, either implement the method in the enumeration class, or implement the method inside the object

Method 1: In Implement the methods in the interface inside the enumeration object

interface info{
    public String getColor();}public enum Color implements info{
    RED{
        @Override
        public String getColor() {return "红色";}
    },
    GREEN{
        @Override
        public String getColor() {return "绿色";}
    },
    BLUE{
        @Override
        public String getColor() {return "蓝色";}
    };}

Method 2: Implement the methods in the interface in the enumeration class

interface info{
    public String getColor();}public enum Color implements info{

    RED,GREEN,BLUE;
    
    @Override
    public String getColor() {
        return null;
    }}

Main method

public class EnumTest {
    public static void main(String[] args) {
        Color color = Color.RED;
        System.out.println(color.getColor());
    }}

Java basic induction enumeration

Enumeration implements abstract methods

In enumeration types, abstract methods can be defined, which are implemented by objects

Enumeration class

public enum Color {
    RED{
        @Override
        public String getColor() {return "红色";}
    },
    GREEN{
        @Override
        public String getColor() {return "绿色";}
    },
    BLUE{
        @Override
        public String getColor() {return "蓝色";}
    };
    //在枚举中定义一个抽象方法,通过枚举对象实现
    public abstract String getColor();}

Main method

public class EnumTest {
    public static void main(String[] args) {
        Color color = Color.BLUE;
        System.out.println(color.getColor());
    }}

Java basic induction enumeration

Enumeration implementation Singleton mode

The enumeration is used to ensure that the data is within the specified range. If there is only one type (one value) in the enumeration, then there is only one object in the enumeration, then you can Implement the singleton pattern.

Enumeration class

public enum Singletion {
    SINGLETION;
    public void Method(){
        System.out.println("使用枚举实现单例模式!!!");
    }}

Main method

public class EnumTest {
    public static void main(String[] args) {
        Singletion singletion=Singletion.SINGLETION;
        singletion.Method();
    }}

Java basic induction enumeration

Collection Class support for enumeration

After JDK1.5, two new subclasses have been added to the Set and Map interfaces:

EnumSet and EnumMap Two subcategories

EnumSet

一个专门Set实现与枚举类型一起使用。 枚举集中的所有元素都必须来自创建集合时明确或隐式指定的单个枚举类型
EnumSet是一个抽象类,不能直接创建实例对象,但是可以通过方法来使用。Java basic induction enumeration
EnumSet.allOf(Class<e> elementType)</e>把一个枚举类型全部填充到集合中去
public static <e extends enum>> EnumSet<e> complementOf(EnumSet<e> s)</e></e></e>创建与指定枚举集具有相同元素类型的枚举集,最初包含此类型的所有元素,该元素 不包含在指定的集合中。
public static <e extends enum>> EnumSet<e> copyOf(EnumSet<e> s)</e></e></e>创建与指定的枚举集相同的元素类型的枚举集,最初包含相同的元素(如果有)

代码

import java.util.EnumSet;public class EnumTest {
    public static void main(String[] args) {
        EnumSet<color> set = EnumSet.allOf(Color.class);//把一个枚举类型全部填充到集合中去
        for (Color c : set) {
            System.out.println(c.name());
        }
    }}</color>

Java basic induction enumeration

EnumMap

EnumMap一个专门Map实现与枚举类型键一起使用。 枚举映射中的所有密钥必须来自创建映射时明确或隐式指定的单个枚举类型。 枚举地图在内部表示为数组。 这种表示非常紧凑和高效。

代码

import java.util.EnumMap;public class EnumTest {
    public static void main(String[] args) {
        EnumMap<color> map = new EnumMap(Color.class);
        map.put(Color.RED, "红色");
        map.put(Color.GREEN, "绿色");
        map.put(Color.BLUE, "蓝色");
        System.out.println(map.get(Color.RED));
    }</color>

Java basic induction enumeration

推荐学习:《java视频教程

The above is the detailed content of Java basic induction enumeration. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete