I'm very new in Java and were wondering and didn't find anything about it.
Can you create enum tuple ?
public enum Status {OPEN : "1", CLOSED: "2", DELETED: "3"}
I will need to access both "OPEN" or "1"
You could always create a custom constructor for your enum..
public enum Status {
OPEN("1"),
CLOSED("2"),
DELETED("3");
private String code;
public Status(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
Then you can access with Status.OPEN.getCode(). This functions as an effective mapping between an enum type and a code value.
You can do something like this:-
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
public enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;
private Currency(int value) {
this.value = value;
}
};
Constructor of enum in java must be private any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.
private int getValue() { return value; }
and get values like this:-
PENNY.getValue(); //returns int 1
Refrence:
Solution by #christopher cover only first part. Creating ENUM.
You will need one more method that match code with enum value:
public static Status byCode(String code){
for(Status s : Status.values()) {
if (s.code.equals(code)) {
return s;
}
}
throw new IllegalArgumentException("Code does not match");
}
now you can get enum value by name and by code.
Related
I am trying to build an object which will be used to communicate with other objects. This communication object should have an enum, these enums include "ORDER_CREATED", "ORDER_CANCELLED" and "ORDER_AT_LOCATION". What I now want to do is assign a value to the enum "ORDER_AT_LOCATION" with a String location. This way there are no blank fields containing "null" if the enum is "ORDER_CREATED".
I am not entirely sure if this is even possible.
I tried using a constructor for one specific enum but didn't have any luck
public class OrderEvent {
private OrderEventTypes eventType;
}
enum OrderEventTypes{
//I want a constructor with String info only for the enum ORDER_AT_LOCATION
ORDER_AT_LOCATION{
String info;
public void ORDER_IN_TRANSIT(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
}
, ORDER_CANCELLED, ORDER_COMPLETED, ORDER_CREATED;
}
the expected result should be that this statement works.
if(eventType.equals("ORDER_AT_LOCATION")) {
System.out.println(eventType.getInfo());
}
if you have any other nice solutions to this I would be very thankful, all the solutions I could come up with were perfectly do-able but not as nice as this would be.
You can create the enum with a constructor which accepts a String value and initialises the info field:
enum OrderEventTypes{
ORDER_AT_LOCATION("ORDER_AT_LOCATION"),
ORDER_CANCELLED,
ORDER_COMPLETED,
ORDER_CREATED;
private final String info;
OrderEventTypes(){
this("");
}
OrderEventTypes(String info){
this.info = info;
}
public String getInfo(){
return this.info;
}
#Override
public String toString() {
return this.info;
}
}
Now when you need to compare, you can use the getter to get the value of the info field:
if("ORDER_AT_LOCATION".equals(eventType.getInfo())){
System.out.println(eventType.getInfo());
}
I am confused at what is going on here. It's a simple thing but for some reason I am getting the name of the enumeration and not the value.
Here is my class :
public class Class1{
public enum SchoolEnum {
01("MIDDLE_SCHOOL");
private String value;
SchoolEnum(String value) {
this.value = value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}
private SchoolEnum schoolEnum = null;
public SchoolEnum getSchoolEnum () {
return schoolEnum;
}
public void setSchoolEnum (SchoolEnum schoolEnum ) {
this.schoolEnum= schoolEnum;
}
}
Calling it in another class via this :
Class1 response = new Class1();
response.setSchoolEnum(Class1.SchoolEnum.valueOf("01"));
Whenever I try to get the value of the 01 Enum, I am simply getting 01 instead of the value MIDDLE_SCHOOL. What is going on here ?
I think your declaration is wrong.
01("MIDDLE_SCHOOL");
Above declaration will give you compile time error. As any variable name can't start with digit.
Some naming suggestions you can use.
_01("MIDDLE_SCHOOL");
ONE("MIDDLE_SCHOOL");
ZERO_ONE("MIDDLE_SCHOOL");
I want to get the enum value by name string,
this the enum code:
package practice;
enum Mobile {
Samsung(400),
Nokia(250),
Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
I can get the class name and the name string
Class enumClass = Class.forName("practice.Mobile");
String name = "Samsung";
how can I get the Samsung value 400 only use enumClass and name?
thanks a lot
You can use something like:
final Mobile mobile = Mobile.valueOf("Samsung");
final int price = mobile.showPrice();
(you do have to change the scope of the method showPrice() to public).
as you may know, there is a valueOf method in every enum, which returns the constant just by resolving the name(read about exceptions when the string is invalid.)
now, since your enum has another fields associated to the constants you need to search its value by matching those fields too...
this is a possible solution using
java 8
public enum ProgramOfStudy {
ComputerScience("CS"),
AutomotiveComputerScience("ACS"),
BusinessInformatics("BI");
public final String shortCut;
ProgramOfStudy(String shortCut) {
this.shortCut = shortCut;
}
public static ProgramOfStudy getByShortCut(String shortCut) {
return Arrays.stream(ProgramOfStudy.values()).filter(v -> v.shortCut.equals(shortCut)).findAny().orElse(null);
}
}
so you can "resolve" the enum by searching its "shortcut"
like
System.out.println(ProgramOfStudy.getByShortCut("CS"));
I created simple enum class in java.
public enum XmlElementsInput {
element_sentenceInput("a");
element_sentence("b");
private final String elementName;
private XmlElementsInput(String name) {
this.elementName = name;
}
public String getElementName() {
return elementName;
}
}
But Netbeans say me: invalid method declaration; return type required, ilegal start of type on line element_sentence("b");. I dont know why? Can you tell me why?
The enum types must separated by comma:
element_sentenceInput("a"),
element_sentence("b");
Use commas to separate enum values, as follows:
public enum XmlElementsInput {
element_sentenceInput("a"),
element_sentence("b");
// Remaining part
}
I have the following enum in Objective-C:
typedef enum {
APIErrorOne = 1,
APIErrorTwo,
APIErrorThree,
APIErrorFour
} APIErrorCode;
I use the indexes to reference an enum from an xml, for example, xml may have error = 2, which maps to APIErrorTwo
My flow is I get an integer from the xml, and run a switch statement as follows:
int errorCode = 3
switch(errorCode){
case APIErrorOne:
//
break;
[...]
}
Seems Java dislikes this kind of enum in a switch statement:
In Java it seems you can't assign indexes to enum members. How can I get a Java equivalent of the above ?
Java enums have a built-in ordinal, which is 0 for the first enum member, 1 for the second, etc.
But enums are classes in Java so you may also assign them a field:
enum APIErrorCode {
APIErrorOne(1),
APIErrorTwo(27),
APIErrorThree(42),
APIErrorFour(54);
private int code;
private APIErrorCode(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
}
One question per post is the general rule here.
But evolving the JB Nizer answer.
public enum APIErrorCode {
APIErrorOne(1),
APIErrorTwo(27),
APIErrorThree(42),
APIErrorFour(54);
private final int code;
private APIErrorCode(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public static APIErrorCode getAPIErrorCodeByCode(int error) {
if(Util.errorMap.containsKey(error)) {
return Util.errorMap.get(error);
}
//Or create some default code
throw new IllegalStateException("Error code not found, code:" + error);
}
//We need a inner class because enum are initialized even before static block
private static class Util {
private static final Map<Integer,APIErrorCode> errorMap = new HashMap<Integer,APIErrorCode>();
static {
for(APIErrorCode code : APIErrorCode.values()){
errorMap.put(code.getCode(), code);
}
}
}
}
Then in your code you can write
int errorCode = 3
switch(APIErrorCode.getAPIErrorCodeByCode(errorCode){
case APIErrorOne:
//
break;
[...]
}