JAVA: Parsing String to static final int value - java

I have simple problem, but I'm not able to fix it. I have this interface...
public interface KeyInput extends Input {
public static final int TEST1 = 0x01;
public static final int TEST2 = 0x02;
}
...this string variable...
String inputString = "TEST1";
...and this method.
public void doSomething(int _input) {
}
I want to parse inputString variable to KeyInput static final int value. So that I could call....
doSomething(KeyInput.parse(inputString));
I know the enum valueOf, but this doesn't work here...

If you have only these two (or any other fixed number of) values, you might just enumerate them in switch:
public static int parse(String input) {
int res = -1;
switch (input) {
"TEST1":
res = TEST1;
break;
"TEST2":
res = TEST2;
break;
// ... other options
default: throw new IllegalArgumentException("unknown string");
}
}
The other option is to keep this values inside some map, so you can do this:
private static final Map <String, Integer> TESTS = new HashMap<>();
static {
TESTS.put("TEST1", 0x01);
TESTS.put("TEST2", 0x02);
// ...
}
public static int parse(String input) {
if (TESTS.containsKey(input))
return TESTS.get(input);
else
throw new IllegalArgumentException("unknown string");
}
Still, if you see the enums as an option in your case, I can consider this solution:
public enum Keys {
TEST1(0x01), TEST2(0x02);
int value;
private Keys(int value) {
this.value = value;
}
public getValue() {
return value;
}
}
Here you'll just do valueOf as you suggesed:
public static int parse(String input) {
return Keys.valueOf(input).getValue();
}
If all these options is now for your case, you should use reflection (though, I'm quite sure, it's not the case):
public static int parse(String input) {
Field[] fields = KeyInput.class.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(fields.getModifiers()) && field.getDeclaringClass().equals(int.class) && field.getName().equals(input)) {
return field.getInt(null);
}
}
throw new IllegalArgumentException("unknown string");
}

Related

How to count a type "object" selected at runtime

I need to count a specific Object, but I'll know which object only at runtime.
Right now I have something like
public class Details {
private String typeOfObjectRequired;
private int numberOfObjectRequired;
}
And in another class I have
public class Container {
private List<Type1> type1List;
private List<Type2> type2List;
private Type3 type3Object;
public int countType1() {
return type1List.size();
}
public int countType2() {
return type2List.size();
}
public int countType3() {
return type3Object.getNumberOfSomething();
}
}
Now I'm doing like this (in a third class that has both Details and Container as attributes)
public boolean hasNumberOfObjectRequired() {
int count = 0;
String type = details.getTypeOfObjectRequired();
if(type.equals("type1")) count = container.countType1();
else if (type.equals("type2")) count = container.countType2();
else if (type.equals("type3")) count = container.countType3();
if (count > details.getNumberOfObJectRequired) return true;
return false;
}
Is there a better way to do this? I don't like to have so many if, also because I have more than just 3 different types.
EDIT:
Right now I have 5 different types, and I always need only one of them.
Basically I want to call different methods based on the String
The Container class could contain a Map of the lists it's composed of:
class Container {
private Map<String, List<?>> lists = new HashMap<>();
private List<TypeOne> first = ...;
private List<TypeTwo> second = ...;
public Container() {
lists.put("type1", first);
lists.put("type2", second);
}
public int count(String type) {
return lists.get(type).size();
}
}
You can grab the size based on the type by calling count:
public boolean hasNumberOfObjectRequired() {
String type = details.getTypeOfObjectRequired();
int requiredCount = details.getNumberOfObjectRequired();
return container.count(type) >= requiredCount;
}
You can use reflection...
public boolean hasNumberOfObjectRequired() {
int count = 0;
String type = details.getTypeOfObjectRequired();
Method m = Container.class.getMethod("countType"+type.charAt(4));
return m.invoke(container) > details.getNumberOfObJectRequired);
}
Or you can use a switch
switch(type){
case "type1":
count = ...
break;
case "type2"
....
}
Even better if type is a int instead of a string

Trying to replace a char by another into a map

I'm trying to replace W by OU only if the char before him is at position 0 of the string and if it's a consonnant and only the first W in the String, ie TWITWIC --> TOUITWIC.
Here is my code (tampon is the input i give to the code into my test):
public class Phonkw {
static Map<String, String> consonnantReplace = new HashMap<String, String>();
static {
consonnantReplace.put("BW", "BOU");
consonnantReplace.put("CW", "COU");
consonnantReplace.put("DW", "DOU");
consonnantReplace.put("FW", "FOU");
consonnantReplace.put("GW","GOU");
consonnantReplace.put("HW","HOU");
consonnantReplace.put("JW", "JOU");
consonnantReplace.put("KW", "KOU");
consonnantReplace.put("LW", "LOU");
consonnantReplace.put("MW", "MOU");
consonnantReplace.put("NW", "NOU");
consonnantReplace.put("PW", "POU");
consonnantReplace.put("QW", "QOU");
consonnantReplace.put("RW", "ROU");
consonnantReplace.put("SW", "SOU");
consonnantReplace.put("TW", "TOU");
consonnantReplace.put("VW","VOU");
consonnantReplace.put("WW", "WOU");
consonnantReplace.put("XW","XOU");
consonnantReplace.put("ZW", "ZOU");
}
public static String phonkw1(final String tampon){
if (tampon==null){
return "";
}
if(consonnantReplace.containsKey(tampon)){
return consonnantReplace.get(tampon);
}
return tampon;
}
}
I think i need to substring tampon at (0,1) but i cant get the value in map byt the substring.
EDIT : RESOLVE.
In case you want to stick to your Map solution, you will indeed need to use substring(). For the lookup, you want to go for substring(0, 2) because that will be the first two characters of the String tampon. However, be aware that this will throw StringIndexOutOfBoundsException in case of single-letter-words, so a guard checking the length would be required.
This is your code modified accordingly:
import java.util.*;
public class Phonkw {
static Map<String, String> consonnantReplace = new HashMap<String, String>();
static {
consonnantReplace.put("BW", "BOU");
consonnantReplace.put("CW", "COU");
consonnantReplace.put("DW", "DOU");
consonnantReplace.put("FW", "FOU");
consonnantReplace.put("GW","GOU");
consonnantReplace.put("HW","HOU");
consonnantReplace.put("JW", "JOU");
consonnantReplace.put("KW", "KOU");
consonnantReplace.put("LW", "LOU");
consonnantReplace.put("MW", "MOU");
consonnantReplace.put("NW", "NOU");
consonnantReplace.put("PW", "POU");
consonnantReplace.put("QW", "QOU");
consonnantReplace.put("RW", "ROU");
consonnantReplace.put("SW", "SOU");
consonnantReplace.put("TW", "TOU");
consonnantReplace.put("VW","VOU");
consonnantReplace.put("WW", "WOU");
consonnantReplace.put("XW","XOU");
consonnantReplace.put("ZW", "ZOU");
}
public static String phonkw1(final String tampon){
if (tampon == null){
return "";
}
if (tampon.length() >= 2) {
final String key = tampon.substring(0, 2);
if (consonnantReplace.containsKey(key)) {
return consonnantReplace.get(key) + tampon.substring(2);
}
}
return tampon;
}
public static void main(final String... args) {
for (final String arg : args)
System.out.println(phonkw1(arg));
}
}
You could actually create your Map<String, String> with a loop. If you do not intend to modify the Map during runtime, you can also wrap it with Collections.unmodifiableMap() to prevent it from accidental modification.
And you might fix the spelling mistake, it's consonant, not consonnant.
The code would then look like this:
import java.util.*;
public class Phonkw {
private static final Map<String, String> consonantReplace = createConsonantReplaceMap();
private static Map<String, String> createConsonantReplaceMap() {
final Map<String, String> map = new HashMap<>();
final String consonants = "BCDFGHJKLMNPQRSTVWXZ";
for (final char consonant : consonants.toCharArray())
map.put(consonant + "W", consonant + "OU");
return Collections.unmodifiableMap(map);
}
public static String phonkw1(final String tampon) {
if (tampon == null) return "";
if (tampon.length() < 2) return tampon;
final String key = tampon.substring(0, 2);
if (consonantReplace.containsKey(key))
return consonantReplace.get(key) + tampon.substring(2);
return tampon;
}
public static void main(final String... args) {
for (final String arg : args)
System.out.println(phonkw1(arg));
}
}
You don't really need a Map if all the entries are uniform replacements. In that case you could directly check, like this:
public class Phonkw {
private static final String CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ";
public static boolean isConsonant(final char c) {
return CONSONANTS.indexOf(c) != -1;
}
public static String phonkw1(final String tampon) {
if (tampon == null) return "";
if (tampon.length() < 2) return tampon;
if (tampon.charAt(1) == 'W' && isConsonant(tampon.charAt(0)))
return tampon.charAt(0) + "OU" + tampon.substring(2);
return tampon;
}
public static void main(final String... args) {
for (final String arg : args)
System.out.println(phonkw1(arg));
}
}
With a regular expression, the code could be even simpler:
public class Phonkw {
public static String phonkw1(final String tampon) {
return tampon == null ? "" : tampon.replaceAll("^([BCDFGHJKLMNPQRSTVWXZ])W", "$1OU");
}
public static void main(final String... args) {
for (final String arg : args)
System.out.println(phonkw1(arg));
}
}
The code below should replace anything before 'W' that is a consonant but only if that consonant is at position 0 in the string.
public class Phonkw {
static Map<String, String> consonnantReplace = new HashMap<String, String>();
static {
consonnantReplace.put("BW", "BOU");
consonnantReplace.put("CW", "COU");
consonnantReplace.put("DW", "DOU");
consonnantReplace.put("FW", "FOU");
consonnantReplace.put("GW", "GOU");
consonnantReplace.put("HW", "HOU");
consonnantReplace.put("JW", "JOU");
consonnantReplace.put("KW", "KOU");
consonnantReplace.put("LW", "LOU");
consonnantReplace.put("MW", "MOU");
consonnantReplace.put("NW", "NOU");
consonnantReplace.put("PW", "POU");
consonnantReplace.put("QW", "QOU");
consonnantReplace.put("RW", "ROU");
consonnantReplace.put("SW", "SOU");
consonnantReplace.put("TW", "TOU");
consonnantReplace.put("VW", "VOU");
consonnantReplace.put("WW", "WOU");
consonnantReplace.put("XW", "XOU");
consonnantReplace.put("ZW", "ZOU");
}
public static String phonkw1(String tampon) {
if (tampon == null) {
return "";
}
Iterator<String> it = consonnantReplace.keySet().iterator();
while (it.hasNext()) {
String s = it.next();
if (tampon.indexOf(s) == 0) {
tampon = tampon.replace(s, consonnantReplace.get(s));
}
}
return tampon;
}
}
A regex might be another solution?
You should use a regular expression to solve this issue, check in the comments for a good regex to use
If you want to use a non-regex solution you could consider the following code. You can indeed use a String.substring, or use String.charAt for a single character
public class Phonkw {
public static String phonkw1(final String tampon){
if (tampon==null){
return "";
}
if (tampon.length() > 1 && isConsonant(tampon.charAt(0)) {//the first character is a consonant
if (tampon.charAt(1) == 'W') {//the 2nd character is a W
return tampon.charAt(0) + "OU" + tampon.substring(2); // not an optimal solution..
}
}
return tampon;
}
public static boolean isConsonant(char c) {
return "BCDFGHJKLMNPQRSTVWXZ".indexOf(c) != -1;
}
}

How to compare an input string with an enum?

I have my below enum -
public enum TestEnum {
h1, h2, h3, h4;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
System.out.println(TestEnum.h1.name());
String ss = "h1";
// check here whether ss is in my enum or not
}
}
Now what I want to check is given a String h1, I need to see whether this String h1 is in my enum or not? How would I do this using the enum?
You should avoid using ordinals for your enum. Rather give a value to each enum constant, and have a field.
So, your enum should look like:
public enum TestEnum {
h1("h1"), h2("h2"), h3("h3"), h4("h4");
private final String value;
TestEnum(String value) { this.value = value; }
public static TestEnum forValue(String value) {
// You can cache the array returned by `values()` in the enum itself
// Or build a map from `String` to `TestEnum` and use that here
for (TestEnum val: values()) {
if (val.value.equals(value)) {
return val;
}
}
}
}
And then for a given String, you can check if it's valid value or not like this:
String value = "h1";
TestEnum enumValue = TestEnum.forValue(value);
if (enumValue == null) {
System.out.println("Invalid value");
}
Easiest approach:
try {
TestEnum.valueOf(ss);
System.out.println("valid");
} catch (IllegalArgumentException e) {
System.out.println("invalid");
}
Setting values for each enum seemed unnecessary to me. Here's a solution that uses toString() instead of .value, which I feel is a bit simpler:
public class tester {
public static void main(String[] args) {
TestEnum enumValue = TestEnum.forValue("X1");
if (enumValue == null) {
System.out.println("Invalid value");
} else {
System.out.println("Good value");
}
}
public enum TestEnum {
X1, X2, X#;
public static TestEnum forValue(String value) {
for (TestEnum val : values())
if (val.toString().equals(value))
return val;
return null;
}
}

Replace String Literals If/elseIf block with Enum

I'm new to using Java Enums and I've read that replace IF logic that compares String literals should be replaced with an Enum. I don't quite understand how to replace my below code with an Enum, any ideas? Based on the col value being passed into applyEQ, I need to do a base the next method call on it's value. I do know the possible values of col ahead of time and I'm using a constants file for now. Should I create an Enum and place it in my Interface of Constants file?
public class FilterHelper implements IFilterHelper {
private final EQuery eQuery;
public FilterHelper(EQuery query) {
eQuery = query;
}
#Override
public void applyEQ(String col, String val) throws Exception {
int return = 0;
if (col.equalsIgnoreCase(EConstants.NAME)) {
ret = Sample.addName(eQuery, val);
} else if (col.equalsIgnoreCase(EConstants.KEYWORDS)) {
ret = Sample.addKey(eQuery, val);
} else if (col.equalsIgnoreCase(EConstants.ROLE)) {
ret = Sample.addRole(eQuery, val);
}
if (return != 0) {
throw new Exception("failed");
}
}
}
EConstants.java
public final class EConstants {
public static final String NAME = "cewName";
public static final String KEYWORDS = "cewKeywords";
public static final String ROLE = "cewRole";
}
First create an enum:
public enum EConstants {
CEWNAME,
CEWROLE,
CEWKEYWORDS;
}
Then convert col String to this enum and use switch:
public void applyEQ(String col, String val) throws Exception {
int ret = 0;
final EConstants constant = EConstants.valueOf(col.toUpperCase());
switch(constant) {
case CEWNAME:
ret = Sample.addName(eQuery, val);
break;
case CEWROLE:
ret = Sample.addRole(eQuery, val);
break;
case CEWKEYWORDS:
ret = Sample.addKey(eQuery, val);
break;
default:
throw new Exception("Unhandled enum constant: " + constant);
}
}
Note that EConstants.valueOf() can throw IllegalArgumentException if col.toUpperCase() does not match any of constant values.
BTW I hate local variables initialized in multiple places (and break keyword), try extracting method:
final EConstants constant = EConstants.valueOf(col.toUpperCase());
final int ret = processSample(val, constant);
And the method itself:
private int processSample(String val, EConstants constant) throws Exception {
switch(constant) {
case CEWNAME:
return Sample.addName(eQuery, val);
case CEWROLE:
return Sample.addRole(eQuery, val);
case CEWKEYWORDS:
return Sample.addKey(eQuery, val);
default:
throw new Exception("Unhandled enum constant: " + constant);
}
}
You can rewrite your EConstants as enum:
public enum EConstants {
NAME, KEYWORDS, ROLE
}
And evaluate condition using switch statement:
// col has type of EConstants
switch (col) {
case NAME:
// do something
break;
case KEYWORDS:
// do something
break;
case ROLE:
// do something
break;
default:
// what to do otherwise
break;
}
The great thing about Java Enums is that they provide language level support for the type safe enum pattern, because among other things it allows you to define methods and even override them. So you could do this:
public enum CewColumn {
NAME("cewName") {
#Override
public int add(EQuery eQuery, String val) {
return Sample.addName(eQuery, val);
}
},
KEYWORDS("cewKeywords") {
#Override
public int add(EQuery eQuery, String val) {
return Sample.addKey(eQuery, val);
}
},
ROLE("cewRole") {
#Override
public int add(EQuery eQuery, String val) {
return Sample.addRole(eQuery, val);
}
};
private final String colName;
private MyColumn(String colName) {
this.colName = colName;
}
private static final Map<String, CewColumn> COLUMNS = new HashMap<>(values().length);
static{
for (CewColumn cewColumn : values()){
COLUMNS.put(cewColumn.colName, cewColumn);
}
}
public abstract int add(EQuery eQuery, String val);
public static CewColumn getCewColumn(String colName){
return COLUMNS.get(colName);
}
}
Then you can use it like this:
CewColumn cewColumn = CewColumn.getCewColumn(colName);
if (cewColumn != null){
int ret = cewColumn.add(eQuery, val);
}
-> You replaced the switch statement with polymorphism!
it is best to create a Enum.
public Enum AvailableCols{
COL_1,
COL_2;
}
and convert the procedure as
public void applyEQ(AvailableCols col, String val) throws Exception {
switch(col){
case COL1:
...
If you still want the string to be preserved you can see the following post
Basically create an enum and change the type of col and use equals() or == to compare the value of col against the enum values. Alternatively you could use a switch statement but I doubt that would make your code more readable for only 3 constants.
Example:
enum EConstants {
NAME,
KEYWORDS,
ROLE;
}
public void applyEQ(EConstants col, String val) throws Exception {
if( col == EConstants.NAME ) {
...
}
....
}
//or
public void applyEQ(EConstants col, String val) throws Exception {
if( EConstants.NAME.equals(col) ) { //col might be null
...
}
....
}
//or
public void applyEQ(EConstants col, String val) throws Exception {
switch( col ) {
case NAME:
...
break;
case ROLE:
...
}
}
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
If your raw data is a string, you will still need to do a string comparison to assign the enum. This might be faster if you do a lot of comparisons on the result data, but if not, it simply adds complication to your code.
You can iterate over the values of the enum like a collection, which gives you an advantage when you need to add constants. That's not bad.
Here is how to do it:
public enum EConstants {
NAME, KEYWORDS, ROLE
}
...
public EConstants setConstant(String from) {
if (from.equalsIgnoreCase("cewName")) {
return NAME;
} else if (col.equalsIgnoreCase("cewKeywords")) {
return KEYWORDS;
} else if (col.equalsIgnoreCase("cewRole")) {
return ROLE;
}
}
You preprocess your data that way and now when you are trying to figure out logic you can use a switch on the enum type value.
Here is a trick for you. No switch/case (just come up with a better name for EConstants).
public enum EConstants {
NAME,
KEYWORDS,
ROLE;
private interface Applier {
void apply(EQuery query, String val);
}
public void apply(EQuery query, String val) {
map.get(this).apply(query, val);
}
private static Map<EConstants, Applier> map = new HashMap<EConstants, EConstants.Applier>();
static {
map.put(NAME, new Applier() {
#Override
public void apply(EQuery query, String val) {
Sample.addName(query, val);
}
});
map.put(KEYWORDS, new Applier() {
#Override
public void apply(EQuery query, String val) {
Sample.addKey(query, val);
}
});
map.put(ROLE, new Applier() {
#Override
public void apply(EQuery query, String val) {
Sample.addRole(query, val);
}
});
}
}
Now you just write:
#Override
public void applyEQ(EConstants econs, String val) {
econs.apply(equery, val);
}

Can I set enum start value in Java?

I use the enum to make a few constants:
enum ids {OPEN, CLOSE};
the OPEN value is zero, but I want it as 100. Is it possible?
Java enums are not like C or C++ enums, which are really just labels for integers.
Java enums are implemented more like classes - and they can even have multiple attributes.
public enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.
See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.
Yes. You can pass the numerical values to the constructor for the enum, like so:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
See the Sun Java Language Guide for more information.
whats about using this way:
public enum HL_COLORS{
YELLOW,
ORANGE;
public int getColorValue() {
switch (this) {
case YELLOW:
return 0xffffff00;
case ORANGE:
return 0xffffa500;
default://YELLOW
return 0xffffff00;
}
}
}
there is only one method ..
you can use static method and pass the Enum as parameter
like:
public enum HL_COLORS{
YELLOW,
ORANGE;
public static int getColorValue(HL_COLORS hl) {
switch (hl) {
case YELLOW:
return 0xffffff00;
case ORANGE:
return 0xffffa500;
default://YELLOW
return 0xffffff00;
}
}
Note that these two ways use less memory and more process units .. I don't say this is the best way but its just another approach.
If you use very big enum types then, following can be useful;
public enum deneme {
UPDATE, UPDATE_FAILED;
private static Map<Integer, deneme> ss = new TreeMap<Integer,deneme>();
private static final int START_VALUE = 100;
private int value;
static {
for(int i=0;i<values().length;i++)
{
values()[i].value = START_VALUE + i;
ss.put(values()[i].value, values()[i]);
}
}
public static deneme fromInt(int i) {
return ss.get(i);
}
public int value() {
return value;
}
}
If you want emulate enum of C/C++ (base num and nexts incrementals):
enum ids {
OPEN, CLOSE;
//
private static final int BASE_ORDINAL = 100;
public int getCode() {
return ordinal() + BASE_ORDINAL;
}
};
public class TestEnum {
public static void main (String... args){
for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) {
System.out.println(i.toString() + " " +
i.ordinal() + " " +
i.getCode());
}
}
}
OPEN 0 100
CLOSE 1 101
The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.
Example:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};
Gives the output:
OPEN: 100
CLOSE: 101
OTHER: 102
Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.
#scottf
An enum is like a Singleton. The JVM creates the instance.
If you would create it by yourself with classes it could be look like that
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
#Override
public String toString(){
return enumValue;
}
}
And could be used like that:
public class HelloWorld{
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
#Override
public String toString(){
return enumValue;
}
}
public static void main(String []args){
System.out.println(MyEnum.ONE);
System.out.println(MyEnum.TWO);
System.out.println(MyEnum.ONE == MyEnum.ONE);
System.out.println("Hello World");
}
}
public class MyClass {
public static void main(String args[]) {
Ids id1 = Ids.OPEN;
System.out.println(id1.getValue());
}
}
enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
#scottf, You probably confused because of the constructor defined in the ENUM.
Let me explain that.
When class loader loads enum class, then enum constructor also called. On what!! Yes, It's called on OPEN and close. With what values 100 for OPEN and 200 for close
Can I have different value?
Yes,
public class MyClass {
public static void main(String args[]) {
Ids id1 = Ids.OPEN;
id1.setValue(2);
System.out.println(id1.getValue());
}
}
enum Ids {
OPEN(100), CLOSE(200);
private int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
public void setValue(int value) { id = value; }
}
But, It's bad practice. enum is used for representing constants like days of week, colors in rainbow i.e such small group of predefined constants.
I think you're confused from looking at C++ enumerators. Java enumerators are different.
This would be the code if you are used to C/C++ enums:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};

Categories

Resources