I have two enums which are related:
Enum1:
public enum HttpStatusCode {
ACCEPTED(202),
OK(200),
CREATED(201),
BAD_REQUEST(400),
NOT_FOUND(404),
METHOD_NOT_ALLOWED(405),
REQUEST_TIMEOUT (408),
FORBIDDEN(403),
CONFLICT(409),
INTERNAL_SERVER_ERROR(500),
NOT_IMPLEMENTED(501);
private int httpStatusCode;
private HttpStatusCode(int name) {
this.httpStatusCode = name;
}
public int getHttpStatusCode() {
return httpStatusCode;
}
}
Enum2:
public enum ProtocolStatusCode {
ACCEPTED(1000),
OK(2000),
CREATED(2001),
BAD_REQUEST(4000)
private int protocolStatusCode;
private ProtocolStatusCode(int protocolStatusCode) {
this.protocolStatusCode = protocolStatusCode;
}
public int getStatusCode() {
return protocolStatusCode;
}
}
These two enums values are related in a mapping, for example
Protocol status code 2000 (OK) has mapping with 200 (OK).
So in my code I will get the ProtocolStatusCode (2000) and corresponding to that I will need HttpStatusCode (200).
I was thinking of maintaing the ProtocolStatusCode enum as
ACCEPTED(1000, 202),
OK(2000, 200)
So like this when I get 2000, I will reverse lookup the enum to get OK and then call a getter to get the second value (200) related to 2000.
Any better approach ??
There are two ways for making comparison of enum members : equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
Overview. EnumMap is a Map implementation that exclusively takes Enum as its keys.
EnumMap is a specialized map implementation that uses only Enum type key. In HashMap, we can use Enum as well as any other object as a key. It doesn't allow storing null key. It allows to store the null keys as well values, but there should be only one null key object and there can be any number of null values.
you can in 2nd enum add a field, which is the type of the first enum. Then you don't have to search through the first enum array to find the right object. Something like:
enum A{
A_FOO(1),
A_BAR(2);
private int code;
private A(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
enum B{
B_FOO(1000,A_FOO),
B_BAR(2000,A_BAR);
private int code;
private A status;
private B(int code, A status) {
this.code = code;
this.status = status;
}
public int getCode() {
return code;
}
public A getStatus() {
return status;
}
}
thus, if the codes in the B enum is unique, you can implement a method like getBbyCode()
then you have B.A
too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With