java中的枚举类

java.lang

Class Enum<E extends Enum<E>>

    • Constructors 
      ModifierConstructor and Description
      protected Enum(String name, int ordinal)

      Sole constructor.

    • All Methods  Static Methods  Instance Methods  Concrete Methods 
      Modifier and TypeMethod and Description
      protected Objectclone()

      Throws CloneNotSupportedException.

      intcompareTo(E o)

      Compares this enum with the specified object for order.

      booleanequals(Object other)

      Returns true if the specified object is equal to this enum constant.

      protected voidfinalize()

      enum classes cannot have finalize methods.

      枚举类不能有finalize方法。

      Class<E>getDeclaringClass()

      Returns the Class object corresponding to this enum constant's enum type.

      返回与此枚举常量的枚举类型相对应的Class对象。

      inthashCode()

      Returns a hash code for this enum constant.

      Stringname()

      Returns the name of this enum constant, exactly as declared in its enum declaration.

      intordinal()

      Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

      返回此枚举常量的序数(其在枚举声明中的位置,其中初始常量的序数为零)。

      StringtoString()

      Returns the name of this enum constant, as contained in the declaration.

      static <T extends Enum<T>>
      T
      valueOf(Class<T> enumType, String name)

      Returns the enum constant of the specified enum type with the specified name.

      返回具有指定名称的指定枚举类型的枚举常量。

 使用实例

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import java.util.*;
public class TestB{

	public static void main(String[] args) throws Exception{
		Scanner in=new Scanner(System.in);
		System.out.print("Enter a size:(SMALL,MEDIUM,LARGE,EXTRA_LARGE)");
		String input=in.next().toUpperCase();
		Size size=Enum.valueOf(Size.class,input);
		System.out.println("abbreviation="+size.getAbbreviation());
		if(size==Size.EXTRA_LARGE)
			System.out.println("Good job--you  paid attention to the _.");
	}
}
enum Size
{
	SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL");
	private Size(String abbreviation){this.abbreviation=abbreviation;}
	public String getAbbreviation(){return abbreviation;}
	private String abbreviation;
}

 

运行结果

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.*;
public class TestB{

	public static void main(String[] args) throws Exception{
		
	for(Size size:Size.values()){
		System.out.println(size+":"+size.getAbbreviation());
	}
	}
}
enum Size
{
	SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL");
	private Size(String abbreviation){this.abbreviation=abbreviation;}
	public String getAbbreviation(){return abbreviation;}
	 private String abbreviation;
}

 

运行结果

常规用法

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.*;
public class TestB{

	public static void main(String[] args) throws Exception{
		
	for(Size size:Size.values()){
		System.out.println(size);
	}
	}
}
enum Size
{
	SMALL,MEDIUM,LARGE,EXTRA_LARGE;
	// private Size(String abbreviation){this.abbreviation=abbreviation;}
	// public String getAbbreviation(){return abbreviation;}
	 // String abbreviation;
}

 

 

 

由于values方法是由编译器插入到enum中的static方法,所以如果你将enum向上转型为Enum,那么将不能调用values方法来遍历enum实例。不过在Class类中有一个getEnumConstants( )方法,即便Enum中没有values方法,也可以通过它遍历enum的实例。

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.*;
public class TestB{

	public static void main(String[] args) throws Exception{
		Size o=Size.SMALL;
	for(Size size:o.getClass().getEnumConstants()){
		System.out.println(size);
	}
	}
}
enum Size
{
	SMALL,MEDIUM,LARGE,EXTRA_LARGE;
	// private Size(String abbreviation){this.abbreviation=abbreviation;}
	// public String getAbbreviation(){return abbreviation;}
	 // String abbreviation;
}

 

enum实现接口
在前面已经提到过,每个enum类,编译器都会让它继承Enum方法,在java中,类又不支持多继承,所以enum类不能再去继承别的类。但是java支持一个类可以实现多个接口。所以enum可以实现多个接口。在java编程思想中说到,实现接口是使enum类子类化的唯一方法。比如下面例子:

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
public class TestB{

	public static void main(String[] args) throws Exception{
		Size o=Size.SMALL;
		o.print();
	for(Size size:o.getClass().getEnumConstants()){
		System.out.println(size);
	}
	}
}
enum Size implements Print   //Print接口不存在,为举例而使用
{
	SMALL,MEDIUM,LARGE,EXTRA_LARGE;
	// private Size(String abbreviation){this.abbreviation=abbreviation;}
	// public String getAbbreviation(){return abbreviation;}
	 // String abbreviation;
	 @Override
	 public void print(){
	 	System.out.println("That's ok");
	 }
}

 

使用接口组织枚举

通过上面的例子,说枚举不能继承一个类,但是有时候我们又想将一个enum的实例通过子类进行分类组织。举个栗子:我们现在想让enum类表示不同种类的食物,但是我们还想让这些枚举类型都依然保持Food类型。这时候可以使用接口将其组织起来,这么实现:

如果这个时候有很多类型,我们还可以使用 “枚举的枚举”,如下:

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
interface Food {
    enum SftapleFood implements  Food{
        RICE, NOODLES, DUMPLINGS, MANTOU
    }
    enum JunkFood implements Food{
        LATIAO, BINGGAN
    }
    enum Drink implements Food{
        COFFEE, TEA, WATER
    }
}
 
enum FoodType {
    SFTAPLE_FOOD(Food.SftapleFood.class),
    JUNK_FOOD(Food.JunkFood.class),
    DRINK(Food.Drink.class);
    private Food[] val;
 
    FoodType(Class<? extends Food> kind)
    {
        val = kind.getEnumConstants();
    }
    public Food[] getFood()
    {
        return val;
    }
}
 
public class Test
{
    public static void main(String[] args) {
        for (Food food : FoodType.JUNK_FOOD.getFood())
        {
            System.out.println(food);
        }
    }
}
/**
* 输出结果:
* LATIAO
* BINGGAN
*/

 

 

枚举实现单例模式

枚举实现的单例除了简单之外,还有两个好处:

线程安全问题:因为懒汉式单例在写的时候如果没有双重检验锁,在多线程的时候会有线程安全的问题,如果使用枚举类,Java虚拟机在加载枚举类的时候,会使用ClassLoader的loadClass方法,这个方法使用了同步代码块来保证线程安全问题。
避免反序列化破坏单例:因为枚举类的反序列化并不通过反射实现。

 

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import java.util.*;
public class TestB{

	public static void main(String[] args) throws Exception{
		Size instance=Size.INSTANCE;
		instance.Test();
	
	}
}
enum Size
{
	INSTANCE;
	void Test(){
		System.out.println("It shows well");
	}
}

 

运行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值