Java Notes: Enumerations

Source: Internet
Author: User

First, the basic knowledge

Enumeration constants are public static members of enumerated types, and their types are enumerated types that declare them. These constants are called self-typed. Because it is a static constant, you can use the relational operator directly to compare the equality of two enumerated constants. Enumeration constant values can also be obtained by the values method and the ValueOf method defined by the enumeration type.

class Solution {    enum  Color {        RED, BLUE, GREEN    }    publicstatic  void  main (string[] args) {        = color.values ();          for (Color c:colors)            System.out.println (c);    }}

An enumeration constant is an object of its enumerated type, and the constructors and methods can be defined when the enumeration type is defined. All enumerations automatically inherit Java.lang.Enum, some of which are as follows:

    • The ordinal method returns the ordinal value of the enumeration constant.
    • The CompareTo method returns the difference between the other enumeration constants of the same type.
    • The Equals method returns equality with other enumeration constants of the same type.
classSolution {enumColor {RED ("#FF0000"), BLUE ("#0000FF"), GREEN ("#00FF00"); PrivateString Code; Color (String code) { This. Code =Code; } String GetCode () {returnCode; }    }     Public Static voidMain (string[] args) {System.out.println (color.valueof ("RED"));//Output RedSystem.out.println (color.valueof ("BLUE"));//Output BlueSystem.out.println (color.valueof ("GREEN"));//Output Greencolor[] Colors=color.values ();  for(Color c:colors) System.out.println (C.ordinal ());  for(Color i:colors) for(Color j:colors) {System.out.println (I.compareto (j));//back to I.ordinal-j.ordinalSystem.out.println (I.equals (j)); }    }}

Java Notes: Enumerations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.