天天看点

java枚举_Java枚举

java枚举

Enumerations was added to Java language in JDK5.

Enumeration

means a list of named constant. In Java, enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using

enum

keyword. Each enumeration constant is public, static and final by default. Even though enumeration defines a class type and have constructors, you do not instantiate an

enum

using

new

. Enumeration variables are used and declared in much a same way as you do a primitive variable.

枚举已添加到JDK5中的Java语言中。

枚举

是指已命名常量的列表。 在Java中,枚举定义了一个类类型。 枚举可以具有构造函数,方法和实例变量。 它是使用

enum

关键字创建的。 默认情况下,每个枚举常量都是public , static和final 。 即使枚举定义了类类型并具有构造函数,您也不会使用

new

实例化

枚举

。 枚举变量的使用和声明方式与原始变量的使用方式几乎相同。

如何定义和使用枚举 (How to Define and Use an Enumeration)

  1. An enumeration can be defined simply by creating a list of enum variable. Let us take an example for list of Subject variable, with different subjects in the list.

    枚举可以简单地通过创建枚举变量列表来定义。 让我们以“主题”变量列表为例,列表中有不同的主题。

    //Enumeration defined
    enum Subject           
    {
    	Java, Cpp, C, Dbms
    }
               
  2. Identifiers Java, Cpp, C and Dbms are called enumeration constants

    . These are public, static and final by default.

    标识符Java,Cpp,C和Dbms称为

    枚举常量 。 默认情况下,它们是public,static和final。
  3. Variables of Enumeration can be defined directly without any new

    keyword.

    枚举变量可以直接定义,而无需任何

    关键字。

枚举示例 (Example of Enumeration)

Lets create an example to define an enumeration and access its constant by using enum reference variable.

让我们创建一个示例来定义枚举,并使用枚举引用变量访问其常量。

enum WeekDays{ 
	SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 
}

class Demo
{
	public static void main(String args[])
	{
		WeekDays wk; 			//wk is an enumeration variable of type WeekDays
		wk = WeekDays.SUNDAY; 	//wk can be assigned only the constants defined under enum type Weekdays
		System.out.println("Today is "+wk);
	}
}
           

Today is SUNDAY

今天是星期日

使用switch语句进行枚举的示例 (Example of Enumeration using switch statement)

Enumeration can be used in switch case to create decision making application, here we have created an enum of restaurants that can be used to pick user choice restaurant.

枚举可用于切换案例以创建决策应用程序,此处我们创建了一个餐厅枚举,可用于选择用户选择的餐厅。

enum Restaurants {
dominos, kfc, pizzahut, paninos, burgerking
}
class Test {
public static void main(String args[])
{
Restaurants r;
r = Restaurants.paninos;
switch(r) { //The name of the enumertion constants are used without their enumeration
type name i.e only r, not Restaurants.r
case dominos: //only constants defined under enum Restaurants can be used
System.out.println("I AM " + r.dominos);
break;
case kfc:
System.out.println("I AM " + r.kfc);
break;
case pizzahut:
System.out.println("I AM " + r.pizzahut);
break;
case paninos:
System.out.println("I AM " + r.paninos);
break;
case burgerking:
System.out.println("I AM " + r.burgerking);
break;
}
}
}
           

I AM PANINOS

我是PANINOS

示例:If-Else中的枚举 (Example : Enumeration in If-Else)

Enumeration can be used in if statement to compare a value with some predefined constants. Here we are using an enumeration with if else statement.

可以在if语句中使用枚举,以将值与一些预定义的常量进行比较。 在这里,我们使用带有if else语句的枚举。

enum WeekDays{ 
	SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 
}

class Demo {
	public static void main(String args[])
	{
		WeekDays weekDays = WeekDays.WEDNESDAY;
		
		if(weekDays == WeekDays.SUNDAY || weekDays == WeekDays.SATURDAY)
			System.out.println("It is Weekend");
		else 
			System.out.println("It is weekday: "+weekDays);
		
	}
}
           

It is weekday: WEDNESDAY

现在是工作日:WEDNESDAY

示例:遍历枚举元素 (Example: Traversing Enumeration Elements)

We can iterate enumeration elements by calling its static method values(). This method returns an array of all the enum constants that further can be iterate using for loop. See the below example.

我们可以通过调用其静态方法values()来迭代枚举元素。 此方法返回所有枚举常量的数组,可以使用for循环进一步对其进行迭代。 请参见以下示例。

enum WeekDays{ 
	SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 
}

class Demo {
	public static void main(String args[])
	{
		WeekDays[] weekDays = WeekDays.values();
		
		for(WeekDays weekday : weekDays ){
			
			System.out.println(weekday);
			
		}	
	}
}
           

SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY

星期日星期一星期二星期三星期四星期五星期六

Values()和ValueOf()方法 (Values() and ValueOf() method)

All the enumerations predefined methods

values()

and

valueOf()

.

values()

method returns an array of enum-type containing all the enumeration constants in it. Its general form is,

所有枚举预定义的方法

values()

valueOf()

values()

方法返回一个包含所有枚举常量的枚举类型数组。 它的一般形式是

valueOf()

method is used to return the enumeration constant whose value is equal to the string passed in as argument while calling this method. It's general form is,

valueOf()

方法用于返回枚举常量,该枚举常量的值等于调用此方法时作为参数传入的字符串。 它的一般形式是

public         static                 enum-type          valueOf                 (String str)
           

使用values()和valueOf()方法进行枚举的示例: (Example of enumeration using values() and valueOf() methods:)

Value and valueOf both are static methods of enum type and can be used to access enum elements. Here we are using both the methods to access the enum elements.

Value和valueOf都是枚举类型的静态方法,可用于访问枚举元素。 在这里,我们使用两种方法来访问枚举元素。

enum Restaurants {
	DOMINOS, KFC, PIZZAHUT, PANINOS, BURGERKING
}
class Demo {
	public static void main(String args[])
	{
		Restaurants r;
		System.out.println("All constants of enum type Restaurants are:");
		Restaurants  rArray[] = Restaurants.values(); //returns an array of constants of type Restaurants
		for(Restaurants  a : rArray) //using foreach loop
			System.out.println(a);

		r = Restaurants.valueOf("DOMINOS");
		System.out.println("It is " + r);
	}
}
           

All constants of enum type Restaurants are: DOMINOS KFC PIZZAHUT PANINOS BURGERKING It is DOMINOS

枚举类型Restaurants的所有常量是:DOMINOS KFC PIZZAHUT PANINOS BURGERKING这是DOMINOS

枚举要记住的要点 (Points to remember about Enumerations)

  1. Enumerations are of class type, and have all the capabilities that a Java class has.

    枚举是类类型的,并且具有Java类所具有的所有功能。

  2. Enumerations can have Constructors, instance Variables, methods and can even implement Interfaces.

    枚举可以具有构造函数,实例变量,方法,甚至可以实现接口。

  3. Enumerations are not instantiated using new

    keyword.

    枚举未使用

    new 关键字实例化。
  4. All Enumerations by default inherit java.lang.Enum

    class.

    默认情况下,所有枚举都继承

    java.lang.Enum 类。

用构造函数,实例变量和方法进行枚举 (Enumeration with Constructor, instance variable and Method)

Enumeration is similar to class except it cannot be instantiated. It can have methods, constructors, variables etc. here in this example, we are creating constructor and method in the enum and accessing its constants value using these.

枚举与类相似,但无法实例化。 它可以具有方法,构造函数,变量等。在此示例中,我们在枚举中创建构造函数和方法,并使用它们访问其常量值。

enum Student
{
	John(11), Bella(10), Sam(13), Viraaj(9);
	private int age;                   //variable defined in enum Student
	int getage() { return age; }  //method defined in enum Student
	private Student(int age)  //constructor defined in enum Student
	{
		this.age= age;
	}
}
class Demo
{
	public static void main( String args[] )
	{
		Student S;
		System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ " years");
	}
}
           

Age of Viraaj is 9 years

Viraaj的年龄是9年

In this example as soon as we declare an enum variable(Student S), the constructor is called once, and it initializes age for every enumeration constant with values specified with them in parenthesis.

在此示例中,一旦我们声明一个枚举变量( Student S ),则构造函数将被调用一次,并且它将使用括号中指定的值初始化每个枚举常量的年龄。

翻译自: https://www.studytonight.com/java/enumerations.php

java枚举