在Java 5中介绍的Enum类的目的是什么? [英] What is the purpose of Enum class which was introduced in Java 5?

查看:97
本文介绍了在Java 5中介绍的Enum类的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的建议:



1)只有在编译之前才存在枚举从来没有听到任何关于它的东西,而它是无处不在,泛型被编译后被删除)



2)或枚举是以某种方式维持向后兼容性的一种方法没有看到这样)。



其他任何建议? (btw,你曾经在你的代码中使用过吗?)



UPD: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html



换句话说,有一个枚举关键字和枚举类。他们都出现在Java 5中。问题:为什么我们需要两者?



第二个问题:为什么枚举成为API的一部分?

解决方案

Java教程


您应该使用枚举类型,只要您需要表示一组固定的常量。这包括自然枚举类型,如我们的太阳系中的行星和数据集,您可以在编译时知道所有可能的值 - 例如菜单上的选项,命令行标志等。


枚举非常有用,是的,我在代码中使用了很多次。






编辑:



...有一个枚举关键字和枚举类。他们都出现在Java 5中。问题:为什么我们需要两者?



这个问题类似于问有一个关键字和对象类,为什么我们需要两个?



两种情况下,关键字基本上都是提示给编译器;你可以把它们当成句法糖,可以节省你的按键,并让编译器做更少的工作(不要猜测你所声明的)。



这个q& a 也是如此。



<你有没有在你的代码中使用它?



答案仍然是是的。特别地,枚举#valueOf()是一种用于解析字符串的静态方法:

  DayOfWeek d = Enum.valueOf(DayOfWeek.class,TUESDAY); 

但当然这样也可以:

  DayOfWeek d = DayOfWeek.valueOf(TUESDAY); 


My suggestions:

1) either enums exist only before compilation (like generics; but I've never heard anything about it whilst it's written everywhere that generics are being erased after compilation)

2) or Enum is a way to maintain backward compatibility in some way (but I don't see that way yet).

Any other suggestions? (btw, have you ever used it in your code?)

UPD: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html

In other words, there's a enum keyword and Enum class. They both appeared in Java 5. The question: why do we need both?

The second question: why Enum became a part of the API?

解决方案

From the Java Tutorials:

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Enums are extremely useful, and yes, I have used them plenty of times in my code.


Edit:

...there's a enum keyword and Enum class. They both appeared in Java 5. The question: why do we need both?

This question is analogous to asking "there's a class keyword and an Object class. Why do we need both?"

In both cases, the keywords are basically hints to the compiler; you could think of them as syntactic sugar that saves you keystrokes, and lets the compiler do less work (by not making it guess about what you're declaring).

See this q&a as well.

...have you ever used it in your code?

The answer is still "yes." In particular, Enum#valueOf() is a static method useful for parsing strings:

DayOfWeek d = Enum.valueOf(DayOfWeek.class, "TUESDAY");

but of course this works, too:

DayOfWeek d = DayOfWeek.valueOf("TUESDAY");

这篇关于在Java 5中介绍的Enum类的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆