search
HomeJavajavaTutorialJava basic induction enumeration

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. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor