gpt4 book ai didi

java - 两个相关的枚举映射?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:00 24 4
gpt4 key购买 nike

我有两个相关的枚举。

枚举 1:

public enum HttpMethodName 
{
GET, POST, PUT, DELETE;
}

枚举2:

public enum ProtocolOperation {
CREATE(1), RETRIEVE(2), UPDATE(3), DELETE(4), NOTIFY(5);


private BigInteger operationId;

public BigInteger getOperationId() {
return operationId;
}

private ProtocolOperation(int operationId) {
this.operationId = BigInteger.valueOf(operationId);
}
}

枚举值映射为:

Create--> POST
Retrieve--> GET
Update--> PUT
Delete--> DELETE
Notify---> POST

所以除了POST之外,值之间存在一对一的映射。可以有两个值的情况 CreateNotify基于条件。

我正在考虑将映射保留为 List :

    public enum HttpMethodName 
{

POST(new List(ProtocolOperation.CREATE, ProtocolOperation.NOTIFY)) ,GET ( new List(ProtocolOperation.RETRIEVE) ) ,
PUT (new List(ProtocolOperation.UPDATE) ,DELETE(new List(ProtocolOperation.DELETE) ;

List<ProtocolOperation > ops;
HttpMethodName (List<ProtocolOperation> ops)
{
this.ops = ops;
}
}

有没有更好的方法??

编辑:

我想从 HttpMethodName <----> ProtocolOperation 映射两种方式

最佳答案

为什么您觉得目前的方法不尽如人意?

在不了解您的担忧的情况下,我只能建议删除样板文件:

import static ProtocolOperation.*;

public enum HttpMethodName {
GET(RETRIEVE),
POST(CREATE, NOTIFY),
PUT(UPDATE),
DELETE(ProtocolOperation.DELETE);

final List<ProtocolOperation> ops;

HttpMethodName(ProtocolOperation... ops) {
this.ops = Collections.unmodifiableList(Arrays.asList(ops));
}
}

更新:

如果你想以两种方式进行映射,首先硬编码从 ProtocolOperationHttpMethodName 的映射是有意义的(因为它不需要列表)并创建一个MttpMethodName 中的简单搜索方法:

public enum ProtocolOperation {
CREATE(1, HttpMethodName.POST),
RETRIEVE(2, HttpMethodName.GET),
UPDATE(3, HttpMethodName.PUT),
DELETE(4, HttpMethodName.DELETE),
NOTIFY(5, HttpMethodName.POST);

private BigInteger operationId;
private HttpMethodName methodName;

public BigInteger getOperationId() {
return operationId;
}

public HttpMethodName getMethodName() {
return methodName;
}

private ProtocolOperation(int operationId, HttpMethodName httpMethodName) {
this.methodName = httpMethodName;
this.operationId = BigInteger.valueOf(operationId);
}
}

public enum HttpMethodName {
GET,
POST,
PUT,
DELETE;

List<ProtocolOperation> getProtocolOperations() {
List<ProtocolOperation> ops = new ArrayList<ProtocolOperation>(2);
for (ProtocolOperation op : ProtocolOperation.values()) {
if (op.getMethodName() == this) {
ops.add(op);
}
}
return ops;
}
}

由于您有常数和少量值,您不需要在 HttpMethodName 中创建最终静态映射来提供向后映射,线性搜索对于您的情况来说足够快。

关于java - 两个相关的枚举映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32709686/

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