枚举ENUM的tostring() valueof()name()和values()用法

x33g5p2x  于2021-12-29 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(289)

从jdk5出现了枚举类后,定义一些字典值可以使用枚举类型;

枚举常用的方法是values():对枚举中的常量值进行遍历;

valueof(String name) :根据名称获取枚举类中定义的常量值;要求字符串跟枚举的常量名必须一致;

获取枚举类中的常量的名称使用枚举对象.name()

枚举类中重写了toString()方法,返回的是枚举常量的名称;

其实toString()和value是相反的一对操作。valueOf是通过名称获取枚举常量对象。而toString()是通过枚举常量获取枚举常量的名称;

  1. package enumTest;
  2. public enum Color {
  3. RED(0,"红色"),
  4. BLUE(1,"蓝色"),
  5. GREEN(2,"绿色"),
  6. ;
  7. // 可以看出这在枚举类型里定义变量和方法和在普通类里面定义方法和变量没有什么区别。唯一要注意的只是变量和方法定义必须放在所有枚举值定义的后面,否则编译器会给出一个错误。
  8. private int code;
  9. private String desc;
  10. Color(int code, String desc) {
  11. this.code = code;
  12. this.desc = desc;
  13. }
  14. /** * 自己定义一个静态方法,通过code返回枚举常量对象 * @param code * @return */
  15. public static Color getValue(int code){
  16. for (Color color: values()) {
  17. if(color.getCode() == code){
  18. return color;
  19. }
  20. }
  21. return null;
  22. }
  23. public int getCode() {
  24. return code;
  25. }
  26. public void setCode(int code) {
  27. this.code = code;
  28. }
  29. public String getDesc() {
  30. return desc;
  31. }
  32. public void setDesc(String desc) {
  33. this.desc = desc;
  34. }
  35. }

测试类

  1. package enumTest;
  2. public class EnumTest {
  3. public static void main(String[] args){
  4. /** * 测试枚举的values() * */
  5. String s = Color.getValue(0).getDesc();
  6. System.out.println("获取的值为:"+ s);
  7. /** * 测试枚举的valueof,里面的值可以是自己定义的枚举常量的名称 * 其中valueOf方法会把一个String类型的名称转变成枚举项,也就是在枚举项中查找字面值和该参数相等的枚举项。 */
  8. Color color =Color.valueOf("GREEN");
  9. System.out.println(color.getDesc());
  10. /** * 测试枚举的toString()方法 */
  11. Color s2 = Color.getValue(0) ;
  12. System.out.println("获取的值为:"+ s2.toString());
  13. }

相关文章