gpt4 book ai didi

java - 枚举的 toString 中的默认大小写

转载 作者:行者123 更新时间:2023-12-01 22:31:54 24 4
gpt4 key购买 nike

我对 Java 中的枚举有些陌生,我正在尝试覆盖 toString() 以便它可以返回枚举的特殊情况,并为每种情况创建代码:

enum TestEnum {
One, Two, Three,
Exclamation, Ampersand, Asterisk;

public String toString() {
if (this == Ampersand) return "&";
if (this == Exclamation) return "!";
if (this == Asterisk) return "*";
return null; // return toString(); ???
}

如果我使用 toString 作为默认返回语句,我显然会得到 StackOverflowError。有没有办法解决这个问题并返回任何未包含在 toString() 中的情况?

最佳答案

Is there a way to get around this and return any cases not included in the toString()?

我想你只是想:

return super.toString();

然后它不会调用自己 - 它只会使用父类(super class)实现。

但是,我会更改实现,使字符串表示成为枚举值中的一个字段,必要时在构建时指定:

enum TestEnum {
One, Two, Three,
Exclamation("!"), Ampersand("&"), Asterisk("*");

private final String name;

private TestEnum(String name) {
this.name = name;
}

private TestEnum() {
name = super.toString();
}

@Override public String toString() {
return name;
}
}

测试:

public class Test {
public static void main(String [] args){
for (TestEnum x : TestEnum.values()) {
System.out.println(x);
}
}
}

输出:

One
Two
Three
!
&
*

关于java - 枚举的 toString 中的默认大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29180081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com