在 Java 枚举上实现 toString [英] Implementing toString on Java enums

查看:24
本文介绍了在 Java 枚举上实现 toString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中似乎可以这样写:

It seems to be possible in Java to write something like this:

 private enum TrafficLight {
  RED,
  GREEN;

  public String toString() {
   return //what should I return here if I want to return
                               //"abc" when red and "def" when green?
  }
 }

现在,我想知道是否可以在枚举值为红色时返回 toString 方法abc"和绿色时返回def".另外,是否可以在 C# 中做到这一点,您可以在哪里做到这一点?:

Now, I'd like to know if it possible to returnin the toString method "abc" when the enum's value is red and "def" when it's green. Also, is it possible to do like in C#, where you can do this?:

 private enum TrafficLight {
  RED = 0,
  GREEN = 15
  ...
 }

我已经尝试过了,但是我遇到了编译器错误.

I've tried this but it but I'm getting compiler errors with it.

谢谢

推荐答案

Ans 1:

enum TrafficLight {
  RED,
  GREEN;

  @Override
  public String toString() {
    switch(this) {
      case RED: return "abc";
      case GREEN: return "def";
      default: throw new IllegalArgumentException();
    }
  }
}

答案 2:

enum TrafficLight {
  RED(0),
  GREEN(15);

  int value;
  TrafficLight(int value) { this.value = value; }
}

这篇关于在 Java 枚举上实现 toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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