sorry for asking such basic question. I am trying some hands on ENUM. below is my code. I am getting some compilation error . Any idea where is the problem. I want SAMPLEMAIL,BULKUSERS,ALLUSERS should be of integer type.
public enum EmailSendingOption {
SAMPLEMAIL, BULKUSERS, ALLUSERS;
private int emailSendingOptionType;
private EmailSendingOption(String optionType) {
int value = Integer.parseInt(optionType.trim());
emailSendingOptionType = value;
}
public int getEmailSendingOption() {
return emailSendingOptionType;
}
}
thanks.
You have defined a constructor but you haven't supplied arguments for each of your Enums.
Looks like your constructor should take an integer too. Saves having to parse a String each time. It's also safer.
e.g.
SAMPLEMAIL(10), etc.
With your constructor looking like:
private int emailSendingOptionType;
private EmailSendingOption(int optionType) {
this.emailSendingOptionType = optionType;
}
You need to make it like this:
public enum EmailSendingOption {
SAMPLEMAIL("1"), BULKUSERS("2"), ALLUSERS("3");
private int emailSendingOptionType;
private EmailSendingOption(String optionType) {
int value = Integer.parseInt(optionType.trim());
emailSendingOptionType = value;
}
public int getEmailSendingOption() {
return emailSendingOptionType;
}
}
enum are not integers in Java, they are objects. There is no sane reason you would pass an integer as a String to a constructor so it can be parsed into an integer. If you want an integer use an integer.
public enum EmailSendingOption {
SAMPLEMAIL(1), BULKUSERS(2), ALLUSERS(101);
private final int emailSendingOptionType;
private EmailSendingOption(int emailSendingOptionType) {
this.emailSendingOptionType = emailSendingOptionType;
}
public int getEmailSendingOption() {
return emailSendingOptionType;
}
}
Since you are providing a custom constructor to your Enum
EmailSendingOption(String optionType)
You need to add those parameter for each Enum constant.
Change it to:
public enum EmailSendingOption
{
SAMPLEMAIL("String"), BULKUSERS("String"), ALLUSERS("String");
...
}
You defined a constructor as needed a String as argument. SAMPLEMAIL this are a static object
of EmailSendingOption.
Related
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.
Just trying to run through some code for an assignment I'm doing. It is probably simple but for the life of me I can't figure out why I get the above error at the first line
(public WaterLog.......).
Later I want to pass it this line:
[ log = new WaterLog(8, damCapacity); ]
Any help would be appreciated, I am new to this sorry.
public class WaterLog(Integer windowSize, Integer maxEntry) {
private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;
public void addEntry(Integer newEntry) throws SimulationException {
theLog.add(0, newEntry);
counter++;
}
public Integer getEntry(Integer index) throws SimulationException {
If (thelog.isEmpty() || thelog.size() < index) {
return null;
}
return thelog.get(index);
}
public Integer variation() throws SimulationException {
int old, recent = 0;
recent = thelog.get(0);
old = thelog.get(thelog.size-1);
return recent-old;
}
public Integer numEntries() {
return counter;
}
}
Assuming SimulationException is defined correctly:
class WaterLog{
private Integer size;
private Integer max ;
private ArrayList<Integer> theLog; //parameterize your lists
private int counter = 0;
public WaterLog(Integer windowSize, Integer maxEntry) //this is the behavior you were looking for
{
this.size = windowSize;
this.max = maxEntry;
theLog = new ArrayList<Integer>(windowSize);
}
public void addEntry(Integer newEntry) throws SimulationException {
theLog.add(0, newEntry);
counter++;
}
public Integer getEntry(Integer index) throws SimulationException {
if (theLog.isEmpty() || theLog.size() < index) { //Java is case sensitive
return null;
}
return theLog.get(index);
}
public Integer variation() throws SimulationException {
int old, recent = 0;
recent = theLog.get(0);
old = theLog.get(theLog.size()-1); //again, watch case, also size is a method
return recent-old;
}
public Integer numEntries() {
return counter;
}
}
See the comments I added.
EDIT: To explain a bit further what was going on, let's take a look at what you were doing.
public class WaterLog(Integer windowSize, Integer maxEntry) {
private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;
You seem to have confused a class with a constructor. The variables you defined were attributes, which was correct. You needed to use the syntax I showed in my answer to create a constructor. For that same reason, you don't have access to variables like windowSize. To remedy this, we allow them to still be defined outside the constructor, but assigned values inside it, where we have access to windowSize and maxEntry.
If you want to pass some parameters to this class you need a constructor. By default Each and EVERY class comes with a default constructor - which is there, you just don't see it ( but can declare it). What you can then do is make an overloaded construcotr ( which takes some arguments ) and this is what you want so..
if you have a class
class WaterLog {
// no constructor
}
the above is really a
class WaterLog {
public WaterLog() {
// this is the constructor - if you do not declare it its still here, you just dont see it. Ofcourse you have option to declare it.
}
}
The overloaded constructor is something like this
class WaterLog {
public WaterLog() {
//default constructor
}
public WaterLog(Integer int, String string, etc...) {
//overloaded constructor
}
}
and the above is what you need in order to pass arguments to this class constructor. I am not briliant at explaining things but if you need more clarification just let me know :)
I have a load of images of musical symbols which I need to do some processing on and for each one I need to get the integer code corresponding to its file name. There are 23 possible file name strings and 23 integer code and there are many images with the same name under different directories.
The solution I have so far is given (abbreviated) below. I have just defined a load of int and String constants and then written a method which is just a huge chain of if statements to do the translation.
What would be a better way to achieve the same effect? The way I've done it seems really awful! I thought about using some kind of Map, but I wasn't sure of the best way to do so.
public class Symbol {
public static final int TREBLE_CLEF = 0;
public static final int BASS_CLEF = 1;
public static final int SEMIBREVE = 2;
// ...
public static final String S_TREBLE_CLEF = "treble-clef";
public static final String S_BASS_CLEF = "bass-clef";
public static final String S_SEMIBREVE = "semibreve";
// ...
public static int stringCodeToIntCode(String strCode) {
if (strCode == S_TREBLE_CLEF) {
return TREBLE_CLEF;
} else if (strCode == S_BASS_CLEF) {
return BASS_CLEF;
} else if (strCode == S_SEMIBREVE) {
return SEMIBREVE;
} //...
else {
return -1;
}
}
}
I think you are looking for Enum where you can have String constant and its value.
Example:
public enum YourEnumClass{
STRING_CONST (5),
STRING_CONST2 (7),
.....
//constructor
//getValue() method
}
read linked tutorial for more details.
enum StringToInt{
TREBLE_CLEF(0),
......
}
Enum is the way to go.
Another example:
public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
private int code;
private Color(int c) {
code = c;
}
public int getCode() {
return code;
}
how about a hashmap
HashMap<String,Integer> hm=new HashMap<String,Integer();
hm.put("treble-clef",0);
//rest
and get it by using this
int value=hm.get("treble-clef");
I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
public final class Connection {
public static final Connection EMAIL = new Connection("email");
public static final Connection PHONE = new Connection("phone");
public static final Connection FAX = new Connection("fax");
/**/
private final String unmodifiableName; //<-- it's final
private String modifiableName;
/*
* The constructor is private so no new connections can be created outside.
*/
private Connection(String name) {
this.unmodifiableName = name;
}
public String getUnmodifiableName() {
return unmodifiableName;
}
public String getModifiableName() {
return modifiableName;
}
public void setModifiableName(String modifiableName) {
this.modifiableName = modifiableName;
}
}
The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as final, and use the constructor to initialize all of them.
For reference, the following code works as expected:
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.get()); // prints "null"
MyEnum.valueA.set(new Integer(42));
System.out.println(MyEnum.valueA.get()); // prints "42"
}
}
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx
Since Java 1.4 doesn't have enums I'm am doing something like this:
public class SomeClass {
public static int SOME_VALUE_1 = 0;
public static int SOME_VALUE_2 = 1;
public static int SOME_VALUE_3 = 2;
public void receiveSomeValue(int someValue) {
// do something
}
}
The caller of receiveSomeValue should pass one those 3 values but he can pass any other int.
If it were an enum the caller could only pass one valid value.
Should receiveSomeValue throw an InvalidValueException?
What are good alternatives to Java 5 enums?
Best to use in pre 1.5 is the Typesafe Enum Pattern best described in the book Effective Java by Josh Bloch. However it has some limitations, especially when you are dealing with different classloaders, serialization and so on.
You can also have a look at the Apache Commons Lang project and espacially the enum class, like John has written. It is an implementation of this pattern and supports building your own enums.
I'd typically create what I call a constant class, some thing like this:
public class MyConstant
{
public static final MyConstant SOME_VALUE = new MyConstant(1);
public static final MyConstant SOME_OTHER_VALUE = new MyConstant(2);
...
private final int id;
private MyConstant(int id)
{
this.id = id;
}
public boolean equal(Object object)
{
...
}
public int hashCode()
{
...
}
}
where equals and hashCode are using the id.
Apache Commons Lang has an Enum class that works well and pretty well covers what Java 5 Enums offer.
If the application code base is going to use lot of enums, then I would prefer following solution, which I have used in my application.
Base Class
public class Enum {
protected int _enumValue;
protected Enum(int enumValue) {
this._enumValue = enumValue;
}
public int Value() {
return this._enumValue;
}
}
Your enumerations will then follow these pattern
Actual Enum
public class DATE_FORMAT extends Enum {
public static final int DDMMYYYY = 1;
public static final int MMDDYYYY = 2;
public static final int YYYYMMDD = 3;
public DATE_FORMAT(int enumValue) {
super(enumValue);
}
}
And your code can consume this enum as follows
String getFormattedDate(DATE_FORMAT format) {
String sDateFormatted = "";
switch (format.Value()) {
case DATE_FORMAT.DDMMYYYY :
break;
case DATE_FORMAT.MMDDYYYY :
break;
case DATE_FORMAT.YYYYMMDD :
break;
default:
break;
}
return sDateFormatted;
}
Caller can use the function as
void callerAPI() {
DATE_FORMAT format = new DATE_FORMAT(DATE_FORMAT.DDMMYYYY);
String sFormattedDate = getFormattedDate(format);
}
This is yet not full proof against intitializing derived Enum objects with any integer value. However it can provide good syntactic guideline to work in non-enum environment.