Java – two related enumeration mappings?
I have two related enumerations
Enum1:
public enum HttpMethodName { GET,POST,PUT,DELETE; }
Enum2:
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); } }
The mapping of enumeration values is:
Create--> POST Retrieve--> GET Update--> PUT Delete--> DELETE Notify---> POST
Therefore, there is a one-to-one mapping between values. In addition to post events, it can create or notify two values according to conditions
I'm considering keeping the mapping as a 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; } }
Is there a better way
Edit:
I will map two methods of protocoloperation from httpmethodname < ---- >
Solution
Why do you find the current method unsatisfactory?
Without your knowledge, I can only suggest deleting the template:
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)); } }
UPD:
If you want to map in two ways, it makes sense to first map the protocol operation to httpmethodname (because no list is required) and create a simple search method in 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,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; } }
Because you have constants and a small number of values, you do not need to create a final static mapping in httpmethodname to provide backward mapping. Linear search is fast enough for your situation