Home  >  Article  >  Java  >  Introduction to the use of the values() method of the enumeration class enum in Java

Introduction to the use of the values() method of the enumeration class enum in Java

黄舟
黄舟Original
2017-09-25 10:34:301670browse

This article mainly introduces the relevant information about the detailed explanation of the values() method of the enumeration class enum in Java. I hope that through this article you can master this part of the content. Friends in need can refer to it

Detailed explanation of the values() method of the enumeration class enum in java

Foreword:

Regarding enumeration, I believe it is very common to use it now. What I mainly write about is a special method in the enumeration, values(). Why is it special? Because this method cannot be found in the API document of Enum. Next let’s look at the specific usage.

Theoretically, this method can convert the enumeration class into an array of enumeration type. Because there is no subscript in the enumeration, we have no way to quickly find the required enumeration class through the subscript. At this time, after converting to an array, we can find the enumeration class we need through the subscript of the array. The code is shown next.

First is our own enumeration class.


public enum EnumDemoFirst { 
 
  RED(1,"hongse"),GREEN(2,"lvse"),YELLOW(3,"huangse"); 
 
  private int code; 
  private String msg; 
   
 
  private EnumDemoFirst(int ordinal, String name) { 
    this.code = ordinal; 
    this.msg = name; 
  } 
  public int getCode() { 
    return code; 
  } 
  public void setCode(int code) { 
    this.code = code; 
  } 
  public String getMsg() { 
    return msg; 
  } 
  public void setMsg(String msg) { 
    this.msg = msg; 
  } 
   
   
}

Then comes the test method,


public class EnumTest { 
 
  public static void main(String[] args) { 
    EnumDemoFirst[] values = EnumDemoFirst.values(); 
    for (EnumDemoFirst enumDemoFirst : values) { 
      System.out.println(enumDemoFirst + "--" + enumDemoFirst.getCode() + "--" + enumDemoFirst.getMsg()); 
      System.out.println("============="); 
    } 
  } 
}

The output at this time is,


RED--1--hongse 
============= 
GREEN--2--lvse 
============= 
YELLOW--3--huangse 
=============

In this case, the enumeration can be easily used through the values() method.

The above is the detailed content of Introduction to the use of the values() method of the enumeration class enum in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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