Java Foundation------Enumeration Common 7 usages __java

Source: Internet
Author: User

DK1.5 introduces a new type--enumeration. In Java it is a "small" function, but to my development has brought "big" convenience.

usage One: Constants

Before JDK1.5, we defined constants as: publicstaticfianl ... Now that you have enumerations, you can group related constants into an enumeration type, and enumerations provide more methods than constants.

public enum Color {RED, GREEN, BLANK, yellow}

usage two: switch

The switch statement before JDK1.6 only supports the Int,char,enum type, and using enumerations makes our code more readable.

enum signal {      green, yellow, red  }   public  class trafficlight {      Signal color = Signal.RED;       public void change ()  {           switch  (color)  {          case red:               color = Signal.GREEN;               break;           case yellow:                color = Signal.RED;               break;           case green:               color = Signal.YELLOW;               break;          &NBSP}       }  } 

usage Three: Add a new method to the enumeration

If you intend to customize your own method, you must add a semicolon at the end of the sequence of enum instances. and Java requirements must first define an instance of an enum.

The public enum Color {red ("red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4);       Member variable private String name;       private int index; Construction method

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.