gpt4 book ai didi

java - 枚举与其他枚举作为类型

转载 作者:行者123 更新时间:2023-11-30 06:13:37 25 4
gpt4 key购买 nike

我想要一个像这样的枚举:

public enum Type {
STRING, INTEGER, BOOLEAN, LIST(Type);

Type t;

Type() { this.t = this; )
Type(Type t) { this.t = t; }

}

这样我就可以为 LIST 输入各种 Type,例如能够调用 Type.LIST(STRING)。这在 Java 中可能吗?

最佳答案

enum 是有限的,您不能拥有未知数量的条目。因此,您不能将 LIST(LIST(LIST(LIST(...))) 作为单独的 Type 枚举。您需要一个类,但这并不意味着您必须实例化必然有很多对象:

这可能是不成熟的优化,但您可以使用享元模式来确保您无法获得超过一个 Type 实例:

package com.example;

public final class Type {

public enum LeafType {
STRING,
INTEGER,
BOOLEAN
}

//Gives you the familiar enum syntax
public static final Type STRING = new Type(LeafType.STRING);
public static final Type INTEGER = new Type(LeafType.INTEGER);
public static final Type BOOLEAN = new Type(LeafType.BOOLEAN);

private final LeafType leafType;

private final Type listType;
private final Object lock = new Object();
// This is the cache that prevents creation of multiple instances

private Type listOfMeType;

private Type(LeafType leafType) {
if (leafType == null) throw new RuntimeException("X");
this.leafType = leafType;
listType = null;
}

private Type(Type type) {
leafType = null;
listType = type;
}

/**
* Get the type that represents a list of this type
*/
public Type list() {
synchronized (lock) {
if (listOfMeType == null) {
listOfMeType = new Type(this);
}
return listOfMeType;
}
}

public boolean isList() {
return listType != null;
}

/**
* If this type is a list, will return what type of list it is
*/
public Type getListType() {
if (!isList()) {
throw new RuntimeException("Not a list");
}
return listType;
}

/**
* If this type is a leaf, will return what type of leaf it is
*/
public LeafType getLeafType() {
if (isList()) {
throw new RuntimeException("Not a leaf");
}
return leafType;
}

@Override
public String toString() {
if (isList()) {
return "LIST(" + getListType() + ")";
}
return getLeafType().toString();
}
}

用法:

简单类型:

Type string = Type.STRING;

列表:

Type stringList = Type.STRING.list();

列表列表:

Type stringListList = Type.STRING.list().list();

并且您永远不会遇到这样的情况:您有两个描述相同类型的 Type 实例,例如:

Type t1 = Type.BOOLEAN.list().list().list();
Type t2 = Type.BOOLEAN.list().list().list();

System.out.println(t1 == t2 ? "Same instance" : "Not same instance");

我添加了 toString 进行调试:

Type listListListInt = Type.INTEGER.list().list().list();
System.out.println(listListListInt);

给予:

LIST(LIST(LIST(INTEGER)))

关于java - 枚举与其他枚举作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723419/

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