ENUMS

I have a few quick questions about using ENUMs - and why they are so good?
After having read the documentation on them on sun.com, and my own textbook notes, I'm still not entirely clear about using them.
I know you should use them when you have a fixed set of constants (such as days of the week, status' for something).
But for the lets say, day variable, why it can't just be a string of "Monday" or whatever.
Do you use ENUMS to stop you from entering something that shouldnt exist?
Someone also has said to use them as they are quite powerful, how exactly?
I'm not sure if I've understood this properly!!

f1d wrote:
I have a few quick questions about using ENUMs - and why they are so good?
After having read the documentation on them on sun.com, and my own textbook notes, I'm still not entirely clear about using them.
I know you should use them when you have a fixed set of constants (such as days of the week, status' for something).
But for the lets say, day variable, why it can't just be a string of "Monday" or whatever.Well, let's try that:
public class DayOfWeek {
    private String day;
    public DayOfWeek(String day) {
        this.day = day;
DayOfWeek appointment = new DayOfWeek("Fooglesday");Uh oh.
Yeah, a user isn't likely to input "Fooglesday", but they might easily input "Satruday".
You could add a bunch of if/else statements or the like to confirm that the value is a known day of the week...but enums are easier.
Do you use ENUMS to stop you from entering something that shouldnt exist?Yes, exactly.
Someone also has said to use them as they are quite powerful, how exactly?
I'm not sure if I've understood this properly!!They're basically a semi-automatic implementation of the typesafe enum pattern. That is to say, they're classes, and have all the advantages as such (so you can define special behavior in them), and they also have a limited set of possible values, which prevents mistakes like the above, and they also have language support, so you can use them with less code (and more clarity).

Similar Messages

  • APEX application or page url  - How to use enum string to replace ID number

    URL to a APEX page is format as ***/f?p=APPLICATION_ID:PAGE_ID:... . Here the APPLIACTION_ID and PAGE_ID are numbers.
    My Question is: Is there a way to replace the numbers by using strings? For example: can I have a URL like /f?p=MY_APPLICATION:MY_PAGE1: ... ? Juts like ENUM in other languages, MY_APPLICATION actually just represent the application id but much more readable since it is a string with a name the user may familar.
    Please help.
    Thank you.

    You can assign an alphanumeric alias to applications and pages using their respective attribute edit forms in the Application Builder. Then you can construct links that use those aliases instead of the IDs. These aliases will generally be preserved in the URL visible in the browser, but not in all cases. You have to deliberately use the aliases in any branch definitions, list item targets, etc. Note that application aliases must be unique within a workspace. Please see the User's Guide for more info.
    Scott

  • Why "null" value is impossible in "switch(val) {case null: }"  for enums?

    I'm wondering why Java 5.0 does not allow null values
    as options in switch statement:
    If type E is "enum" then the following language construction is
    not allowed:
    E val;
    switch(val) {
       case A:
         break;
       case B:
           break;
       case null:   // this is not allowed
            break;
    }Can somebody explain me why Java does not support it? I beleave that
    some serious reasons were for that.
    As we know enum types can have "null" values and in case I use nulls
    for my enumerations the code with "switch" statement becomes quite urgly because it is necessary to handle 2 separate execution paths:
    null and not null.
    Thanks

    I really don�t know too much about 1.5, but I can tell you that for 1.4 the switch receives as a parameter an int or anything that can be casted automatically to an int. Therefore you can�t never use null cause int, char, short, byte can�t never take as a value null.

  • How to get I32 enum text out of a control (i/p terminal config, active edge of DAQmx vis)

    Hi,
     I am using DAQmx VIs create channel.vi and sample clock.vi, they have inputs (input terminal configuration) and (active edge) both are I32 and have enum looking drop down options. i want to use those text values to put into my excel file, but they give out numeric codes related to respective option. is it possible to get the text as it is.
    it is not an enum but I32 which looks like enum..
    plz help..
    Thanks
    Solved!
    Go to Solution.

    Note: This assumes that you have an actual control on the VI. If you have a
    block diagram constant, then that won't actually work. In this case to get the actual text you need to pick from list of text items. To further complicate things, the actual values that are generated are not sequential. You can use either a case structure or a 2-step lookup.
    Attachments:
    Example_VI.png ‏7 KB

  • Using static .values() method of Enum in Generic Class

    Hi *,
    I tried to do the following:
    public class AClass<E extends Enum<E> >  {
         public AClass() {
              E[] values = E.values(); // this DOESN'T work
              for (E e : values) { /* do something */ }
    }This is not possible. But how can I access all Enum constants if I use
    an Enum type parameter in a Generic class?
    Thanks for your help ;-) Stephan

    Here's a possible workaround. The generic class isn't adding much in this case; I originally wrote it as a static method that you simply passed the class to:
    public class Test21
      public static enum TestEnum { A, B, C };
      public static class AClass<E extends Enum<E>>
        private Class<E> clazz;
        public AClass(Class<E> _clazz)
        {  clazz = _clazz;  }
        public Class<E> getClazz()
        {  return clazz;  }
        public void printConstants()
          for (E e : clazz.getEnumConstants())
            System.out.println(e.toString());
      public static void main(String[] argv)
        AClass<TestEnum> a = new AClass<TestEnum>(TestEnum.class);
        a.printConstants();
    }

  • Sun's demo using enum doesn't seem to work for me

    I'm trying to run a demo from the Sun website, http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html, which includes the enum statement:
    public class SwitchEnumDemo {
        public enum Month { JANUARY, FEBRUARY, MARCH, APRIL,
                            MAY, JUNE, JULY, AUGUST, SEPTEMBER,
                            OCTOBER, NOVEMBER, DECEMBER }
        public static void main(String[] args) {
            Month month = Month.FEBRUARY;
            int year = 2000;
            int numDays = 0;
            switch (month) {
                case JANUARY:
                    // etc etc ...
            System.out.println("Number of Days = " + numDays);
    }However, copying-and-pasting the code into NetBeans, I get an error on the enum declaration stating: '';' expected. Warning: as of release 1.5, 'enum' is a keyword and may not be used as an identifier'. Well... I know that. Isn't that why I'm using it in the first place? Or am I confused?
    I'm using NeBeans 5.0 on Java 1.5.0_06.
    Any advice?
    Question 2: Once I get this thing working, is there any way I can get the month as an input from the user, without needing a long block stating
    if (input = "January") month = Month.JANUARY;
    else if (input = "Feburary") month = Month.FEBURARY;
      //etc etcThat is, can the string representation of a month be somehow kept within the enumerated Month itself, and that be used to check the user's input?
    Thanks for any advice!

    However, copying-and-pasting the code into NetBeans,
    I get an error on the enum declaration stating:
    '';' expected. Warning: as of release 1.5, 'enum'
    is a keyword and may not be used as an
    identifier'. Well... I know that. Isn't
    that why I'm using it in the first place? Or am I
    confused?
    I'm using NeBeans 5.0 on Java 1.5.0_06.I can't say for sure about that; it seems very odd. However, I do know that my IDE will warn me about those sorts of things if I configure my project for pre-1.5 operation. It allows me to say a project is for Java 1.4 even if I'm using a 1.5 JVM and will mention things like that so that forward compatibility can be considered. I don't suppose this could be the case with your situation?
    You might want to search for all instances of "enum" in your code, though, because it's hard to imagine the one instance which appears in the snippet you posted causing problems.
    Question 2: Once I get this thing working, is there
    any way I can get the month as an input from the
    user, without needing a long block stating{snip}
    Well, in this case you can just do
    for (Month m : Month.values())
        if (m.toString().equalsIgnoreCase(input))
            month = m;
            break;
    }or you can build a Map<String,Month> if you're looking for case-sensitive comparison.
    In general, however, you can put pretty much anything into an enum:
    public enum SomeEnum
        A(0),
        B(0),
        C(1),
        D(0),
        E(2);
        private int value;
        SomeEnum(int value)
            this.value = value;
        public int getValue()
            return value;
    // the following is perfectly legal
    SomeEnum e = methodThatReturnsSomeEnum();
    System.out.println(e.getValue());and you could use that to put some form of identifier in the enumeration object. I have a class around here somewhere which uses an enum to enumerate the operators in an expression parser; the Operator enum constructor accepts an int specifying the operator precedence.

  • Importing  Through DTW : "Invalid ItemName'M'  in Enum 'BO Gender Types

    Dear Members,
    I am trying to import in a Business Partner,the contact person in which the gender and date of birth is to be imported.?its showing an error named "Invalid Item Name'M'  in Enum 'BO Gender Types 65171.
    Can anyone help me in this regard to import through template.
    Thanks ,
    Venkatesh.R

    Hi sudha,
    Thanks a lot,one of my issues has been solved,can you tell me how to import similarly for date of birth.
    Regards,
    Venkatesh.R

  • Just checking on another odd feature: Typedef enum Property Node "Value" not reflecting changes in the Typedef?

    Just encountered this odd behavior in LV 2011 which I reduced to the following example:
    - create a new VI and drop an enum control on te FP.
    - make this control a typedef and open the corresponding typedef
    - create a "case 1" item and a "case 2" item
    - save the typedef (I used the name Typedef Control 1) and CLOSE it (this is to allow updating of the original control).
    - drop a case structure on the diagram and connect the enum to it:
    So far so good. Now create a "Value" Property node for the enum and use it instead of the terminal:
    If I now go back to the typedef and add a "case 3" item, save the typedef and close it, the control is updated, but the Property node is not.
    How do I know that? For one, the Case Structure contextual menu does not offer to create a case for every value. Also, if I add a "case 3" case manually, it turns red.
    Luckily, the magic Ctrl-R key stroke actually does solve this problem.
    Tested in LV 2011.

    By Ctrl-R trick do you simply mean running the VI?  That is one way to force a recompile, but if you hold down Ctrl while pressing the run button you can recompile without running.  This should not be "dangerous" in any situation.
    As you have drawn your example, I see no reason not to use a local in that situation (ok, maybe for vanity).  Still, I view the behavior you describe as a bug, and it should certainly be fixed for the benefit of local haters out there.  You have to be a little careful where you draw the line between what gets handled in real time and what gets handled only at compile time.

  • Looking for an alternative to an enum (or any non trivial type)

    Hi. I am making a class to manage geometric points, as in [x, y, z]. some languages, such as scripting language 'adobe actionscript' support certain special values such as NaN (or 'not a number'), and I can do things such as
    var _some_var:Number = Number.NaN;
    the previous sentence is something like assigning null to a pointer. NaN is not a valid value, so I can not operate with a var that has nan as a value.
    I want to do something like that in my class, but I can not use a number value and then say, 'this value is never gonna happen by itself, so if the var has that value is because is in nan state. for any value that I choose, if is a valid value, will be enough
    to consider it as an invalid alternative. instead of that, the vars are handled in pairs, so for each numeric coordinate, such as x, there is also a bool that says if the numeric value is defined
    in each point, there are the x, y and z coordinates, plus defx, defy and defz.
    the constructor is something like
    point() {
    x= 0;
    y= 0;
    z= 0;
    defx = false;
    defy=false;
    defz=false
    and since all vars are private, I use accessors such as
    setX(double _x) {
    x = _x;
    defX = true;
    so how do I assign a NaN to a var that has already a value?, or, how do I set the var 'defX' to false again?
    since setX(_some_value) is the same as x = _some_value, the idea would be that I could write something like
    setX(NaN), and that would 'undefine' X.
    since I can overload functions, and create functions with different prototypes for different types of values, even though the functions are called the same way, that's what I am doing.
    I had two choices: the first one is (copy paste from my file)
    //#ifndef _nan
    //#define _nan
    //#define NaN "NaN"
    //#endif
    not the one I chose because it does not seem better than my second choice (that's why it appears as a comment), or does not solve the problem I have with the choices I have thought so far:
    (in file 'especiales.h')
    #ifndef _especiales
    #define _especiales
    enum EEspecial {NaN};
    #endif
    and in the file for the point definition (as inline functions)
    void setX(double _x) {
                    x = _x;
                    defX = true;
            void setX(EEspecial _e) {
                    if (_e == NaN)
                        defX = false;
                    else
                        throw coordIndefException();
            double getX();
            bool definidoX() {return defX;}
    it works, it does not throw an error or there are no syntax problems; but there is a problem in my head. In the previous sentences there are two functions, one that takes a numeric value and sets it in x, and sets x as defined. on that receives not a numeric
    value but a special value, that if it turn out to be nan, will unset the x var, and set it as undefined.I checked it with these simple lines:
        geometriaPunto _ensayo;
       try {
            _ensayo.setX(NaN);
            cout << _ensayo.getX() << "\n";
        } catch (exception _e) {
            cout << _e.what() << "\n";
    this works fine. if I place a 0 in setX, it will print 0. if I place a NaN in the parenthesis, it will write the exception name. This works fine. But as far as I know, all basic var types, and all enums, also have implicit conversions to numeric values.
    so even though it works here, as I understand, telling it setX(0) is the same as setX(NaN) (which would be the implicit conversion of NaN, since is the first value in the enum). none of those are double (because I did not wrote it as setX(0.0) ), so my guess
    is that even though it works here, it was just luck, and some other c compile may understand it different, since there is not much difference between function_name(int) or function_name(enum_type)
    what would be the best way, most clear way to overload 'setX()' so it does accept a type that can not be confused with a numeric value, yet it does not make my code way more obscure and does not create ambiguity?
    tnx

    this is the last post I will make on this thread, as I find your answers useless and I already have what I need, but concerning your answers:
    "You said it worked for you in your 'adobe actionscript' code - why wouldn't the same technique work in C++ code? Number.NaN is a Number value, and it doesn't prevent you from doing operations in a var that holds that value - but that didn't
    seem to concern you before."
    have you ever worked with actionscript or did you just post because you had to post anything. yes, I can assign NaN to a numeric var in actionscript, just like I can assign null to a pointer. null is a value (0), if I add something to a var that has null,
    it will not have null anymore, if the compiler or the executable don't verify this behavior that should throw an exception. In actionscript, if a var has nan and I add something to it, it will still have nan, because nan is not a value, is a state, and probably
    actionscriopt also handles numeric vars with some other types of vars, to make these kind of validations. If I add 1 to garbage, I will still have garbage, and if I choose a random value to be chosen as nan, I or anybody else can not assure this value will
    not be the result of a valid operation
    2. "Is your question about C#, and not C++? If it is, you are in the wrong forum."
    why do you ask, did you see the previous sentences written in c#, or do you still have to answer crap if you don't answer something related to the question. if somebody has been writing things in other languages (including java or the same actionscript,
    which support that kind of behavior for properties and accessors), seems logic that I want to maintain that programing style, which will help somebody who also has been writing in those languages and then tries to read this new source, written in c++

  • How to use in enums in multiple places?

    How does one use an enum set in multiple places in a vi?
    I have resorted to just copying an existing one when I need the same set of enum values in a different spot, but doing it this way will be a big hassle if/when I want to add items to the enum, because I would have to locate every copy of the enum and update them idividually.
    Is it possible?

    It's not so much the "custom control" part as it is the typedef part. A typedef enforces the datatype for all its instances, including constants, so changing it will propogate through your entire code. To create it the easiest way is to create a front panel enum control and then right click it and select Advanced>>Customize. You can then change it into a typedef and save it under any name you want.
    From this point on, you can simply use that typedef in your code.
    To learn more about LabVIEW, I suggest you try searching this site and google for LabVIEW tutorials. Here, here, here, here and here are a few you can start with and here are some tutorial videos. You can also contact your local NI office and join one of their courses.
    In addition, I suggest you read the LabVIEW style guide and the LabVIEW user manual (Help>>Search the LabVIEW Bookshelf).
    Try to take over the world!

  • How do I make one enum depend on the selection of another?

    Suppose I have 5 enums, say A, B, C, D, E. Each has entries different from the others. I'd like to have a 2nd enum with the entries "A,B,C,D,E". When the user selects one of the 2nd enum entries, I'd like the user to be presented with the corresponding enum from the group of 5.
    The context is this: the 2nd enum has entries like "Status Register" and "Event Register", and 3 others. Each register has different bits, like "motion complete" and "forward limit". I'd like the user to be able to select the register in one enum, and show that register's bit names in the other enum.
    -Jeff

    You could also use Rings as the controls on th efront panel. When the user selects the group programmatically change the value of the ring. You would need to keep track of the current group selection so that when you actually use the value from the ring you can typecast it back to the correct ENUM type and value.
    Another option would be to show/hide the controls based on the group selection.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • How can I establish an enum typedef for use with state machines and action engines?

    Hey all--
    I have an action engine with several instances.  Any time that I add a method to the engine, I have to modify all of the calling code to update the constant that determines the method being called.  There must be a smarter way to address this problem but my LV experience is insufficient to identify it.  Can any of you wiz-bangs tell me if it is possible to make a type def (I can do this) and use it with each instance of the action engine call so that changing any instance also updates the typedef?
    Thanks.

    Take your enumerator.  If it is not a control (ie constant), change it to a control.
    Under File Menu, select New > Custom Control.
    Move (or copy) your Enum Control to the Custom Control.  Change the Control to Strict Type Def (the selection to the right of the wrench).  Save it.
    (EDIT: ** OOps, the picture shows the wrong one.. sorry**)
    Copy that new Strict Type Def control to your code.
    See images below.
    OR.. If you're using LV8.x, and using a project, I would recomment that you do it from within your project explorer.  Simply insert a new "Control".  The rest of the steps are similar, except that you can insert it from your project. 
    R
    Message Edited by JoeLabView on 07-08-2008 06:47 PM
    Attachments:
    TypeDef.PNG ‏33 KB

  • What's the deal with enums?

    Hello,
    I'm trying to familiarise myself with the new Java features that project Tiger (Java 1.5) will introduce. I come from a C++ programming background. I very briefly studied enums whilst I learned C++ and never used them in my programs, so I was, quite frankly, relieved when I learned that Java didn't support them.
    But now it does.
    I'm wondering, from a software design and engineering perspective, what benefit enums will add to the Java language and software engineering in general. I have read some pleas and arguments for enums. As I understand those arguments, proponents feel that minor ledgibility improvements to switch statements (which some OO programmers don't use on the basis that it weakens the object-orientedness through its goto-esque break statements) necessitate the addition of a whole other structure.
    Out of curiosity, wouldn't it be more advantageous for Sun to put their efforts into supporting constant strings in switches in addition to primitive data types if people are so concerned with clarity?
    I fail to understand what enums will do that constant string arrays or constant values cannot. I would like to think that Sun wouldn't add C++ features unless if there was a reason to do so, so I believe that there are good reasons to introduce this feature.
    Please help clarify this confusion.
    Thank you!

    Comments on the previous posting inline. Note: I'll go off on a few tangents, but try to always return to the issue of enums. The fact that I go off on tangents (related initially to an enum type example) should show that enums help eliminate numerous problems.
    Fair enough, but wouldn't this accomplish the same thing in
    a slightly wordier wayPretty much. But you still have the validation code in there yourself:
    currentDirection = ( direction > 0 && direction < 5 ? direction : 0 );People can still accidentally enter an invalid value, and it won't get caught by the compiler. So, I could call set(Compass.WEST) and hope/expect that is equivalent to set(Direction.LEFT). This will only occur if both Compass.WEST and Direction.LEFT are the same int value. If they are not, then we are in trouble. Worse, still if Compass.WEST and Direction.RIGHT are the same value, the code will compile, and run without any illegal value flagging, but our traveller will go off in the wrong direction.
    Error handling tangent: Given the implementation, the error handling is not performed in set, rather the illegal value is captured as a zero, which must be dealt with at a later time - say in a switch statement that calls get. This is not a good idea - it increases the "distance" between the error occuring (bad call to set) and the error being detected (if xInt != 0). The larger the distance, the harder debugging is. If you throw an exception in set the bug is immediately flagged. With enums, none of this should be necessary.
    Implementation tangent: set, get and currentDirection are static. This is not a good idea - it only allows one direction. If you have multiple travellers, each would have a Direction object, but (sticking with constants) UP, etc. would still be static.
    I keep the switch statement in my enum workaround, but I believe that
    the second reply suggested that enum could altogether eliminate the
    use for switch statements. How exactly would it do that?enum in its simplest form would not remove switch. However, using an extension of the type-safe enum idiom (i.e. the current Java approach to enums), you can embed direction specific logic in each of the "enum" members. If I understand the enum-spec correcly, this will also be possible with the Java 1.5 enum language facility.
    So, for an example, sticking with the domain: Consider a class Location, with x and y elements, and a Direction. The non-OO, non-enum approach would be as follows:
    class Location {
        int x,y;
        void move (final int direction) {
            switch (direction) {
                case UP:
                    --y;
                    break;
                case DOWN:
                    ++y;
                    break;
                case LEFT;
                    --x;
                    break;
                case RIGHT:
                    ++x;
                    break;
                default;
                    throw new RuntimeException("Invalid direction " + direction);
    class Direction {
        public static final int UP = 1;
        public static final int DOWN = 2;
        public static final int LEFT = 3;
        public static final int RIGHT = 4;
    }Note that I've deliberately been loose with my visibility. All logic is in Location, and Direction is dumb. If we go with a type safe-enum idiom, we get:
    class Location {
        int x,y;
        void move (final Direction direction) {
            if (direction == Direction.UP) {
                --y;
            } else if (direction == Direction.DOWN) {
                ++y;
            } else if (direction == Direction.LEFT) {
                --x;
            } else if (direction == Direction.RIGHT) {
                ++x;
            } else { // direction is null
                throw new NullPointerException("null direction");
    class Direction {
        public static final Direction UP = new Direction();
        public static final Direction DOWN = new Direction();
        public static final Direction LEFT = new Direction();
        public static final Direction RIGHT = new Direction();
        private Direction () {} // the ctor is private to limit instances
    }This code is a rewrite of the int approach, but is "type-safe". We've moved from switch to if as we can't switch on object references. Note: there is still error handling code, as you're not "null-safe" (I don't know what the Java 1.5 spec says about this)
    Little else has changed - the responsibilities are still the same. We can address this by going OO, which removes the if (formerly a switch) statement, but does couple the classes.
    class Location {
        int x,y;
        void move (final Direction direction) {
            direction.move(this);
    class Direction {
        private final int xOffset, yOffset;
        private Direction (final int xOffset, final int yOffset) {
            this.xOffset = xOffset;
            this.yOffset = yOffset;
        public static final Direction UP = new Direction(0,1);
        public static final Direction DOWN = new Direction(0,-1);
        public static final Direction LEFT = new Direction(-1,0);
        public static final Direction RIGHT = new Direction(1,0);
        void move(final Location location) {
            location.x += xOffset;
            location.y += yOffset;
    }This removes any conditional logic, embedding (constructor parameterised) logic within Direction. It also eliminates the "null-safe" check, as direction.move(this) will throw an NPE if a null is passed.
    Also, I've read some things saying that enum reduces 'boilerplate'
    code. What exactly does that and 'boilerplate' mean?The Direction class is an example of the type-safe enum approach currently used in Java. It has been enhanced with logic for movement. Even if I dropped this logic, there is still functionality worth adding to the Direction class - a toString method that returns one of "UP", "DOWN", etc (shown next); a way to serialize the object and retain reference equality - you have to write a readResolve method (not shown).
    class Direction {
        private final String name;
        private Direction (final String name) {
            this.name = name;
        public static final Direction UP = new Direction("UP");
        public static final Direction DOWN = new Direction("DOWN");
        public static final Direction LEFT = new Direction("LEFT");
        public static final Direction RIGHT = new Direction("RIGHT");
        public String toString() {
            return name;
    }Once you've written this code for one type-safe enum, you've written them for them all. You copy-cut-paste, and rename the class/elements. All this code is predictable. It is "boiler plate". Now, if you gave me a compiler that generated all this code for me, when I present it with
    enum Direction {UP, DOWN, LEFT, RIGHT}; then I've got something that reduces my boiler plate code to zip.... Enter the Java 1.5 compiler.

  • What's the best way to use an enum to validate statuses

    I am trying to write and use an enum to represent a status code and validate status code values. Ultimately the input data from another system and the database will be 1 or 2 i.e.the indexes and the java code will use the LIVE and CANCELLED when referring to the status. The code I have written
    public class TestEntityStatus {
         private static EntityStatusImpl es;
         public static void main(final String args[]){
                    es =  new EntityStatusImpl();  
                    es.setStatusCode("1"); // valid test
                    es.setStatusCode("3"); // invalid test
    }The EntityStatusImpl class:
    public class EntityStatusImpl {
        private String statusCode;
        public EntityStatusImpl() {
        public final String getStatusCode() {
            return statusCode;
        public final void setStatusCode(final String statusCode) {
             String allStsIndexesAsRegExpr = "[";                                                                                 //
                EntityStatus allStatuses [] = EntityStatus.values();                                                     // would like to 
                for(EntityStatus e : allStatuses)                                                                                // put this code
                    allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + e.getStatusCode();   // in the enum
                allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + "]";                                        // EntityStatus
                System.out.println(" allStsIndexesAsRegExpr = " + allStsIndexesAsRegExpr);           //
                 if (statusCode.matches(allStsIndexesAsRegExpr)) {
                     this.statusCode = statusCode;          
                 else {
                      throw new IllegalArgumentException("Entity status " + statusCode + " is invalid");     
    }The EntityStatus enum has a method "getAllIndexesAsRegex" which I would like to call. However, my understanding of enums is preventing me from doing so.
    If I declared an EntityStatus, I expected that I would be able to get all of the indexes back as follows in
    EntityStatus x;
    x.getAllIndexesAsRegex();
    Instead I have to copied the code from the enum into the setStatusCode method above, where it works but does not seem to be in the right place.
    public enum EntityStatus {
                     LIVE(1), CANCELLED(2);
                     private int index;
                 private EntityStatus(int index) {
                     this.index = index;
                  public int getStatusCode(){
                           return index; 
                  public String getAllIndexesAsRegex(){
                       String output = "[";
                       PromiseStatus allStatuses [] = PromiseStatus.values();
                       for(PromiseStatus p : allStatuses)
                            output = output + p.getStatusCode();
                       output = output + "]";
                       return output;
         }The java tutorial doesn't seem to throw much light on this type of application of enums for me, neither does Herbert Schilt's excellent book on Java 5.
    Can anyone spot any flaws in my logic or suggest better ways of achieving this?

    If you want to ensure type safety and retrict the user to a range of values it seems to me you are over complicating
    the implementation. Simply change your Impl class accessor and mutator methods to accept and return the enum
    type respectively. For example:
    private EntityStatus entityStatus;
    public EntityStatus getEntityStatus()
       return entityStatus;
    public void setEntityStatus(EntityStatus entityStatus)
      if (entityStatus == null)
        throw new IllegalArgumentException("Invalid entity status!");
      this.entityStatus = entityStatus;
    }The one downside is that you are retrieving the actual underlying enum values from external source systems which you need to map back to your
    enum types. Unfortunately the Enum class does not have a method that will return what you need (the valueOf method returns the enum type
    based on the enum name). However you can provide a method in your enum class that will map the external source values to the enum. Below is
    one such implemetation.
    import java.util.HashMap;
    import java.util.Map;
    public enum EntityStatus
      LIVE("1"),
      CANCELLED("2");
      private String statusCode;
      private static Map<String,EntityStatus> enumMap = new HashMap<String,EntityStatus>(EntityStatus.values().length);
      static
        enumMap.put(LIVE.getStatusCode(),LIVE);
        enumMap.put(CANCELLED.getStatusCode(),CANCELLED);
      private EntityStatus(String statusCode)
        this.statusCode = statusCode;
      public String getStatusCode()
        return statusCode;
      public static synchronized EntityStatus deriveObject(String statusCode)
        return enumMap.get(statusCode);
    }Below is a usage example:
      public static void main(String args[])
        EntityStatus status1 = EntityStatus.deriveObject("1");
        EntityStatus status2 = EntityStatus.deriveObject("2");
        EntityStatus status3 = EntityStatus.deriveObject("3");
        System.out.println(status1);
        System.out.println(status2);
        System.out.println(status3);
      }

  • Enum class not supported for switch() statement in 12.4 beta?

    Hi fellow 12.4 beta testers,
    It would appear "enum class" isn't supported for switch() statements in the 12.4 beta. This compiles fine under clang and g++. Will this be fixed for the final release? This currently causes compile errors for us, since __cplusplus >= 201103L evaluates to true, so our code uses "enum class" instead of plain "enum". It looks like the C++11 standard says it should be supported:
       Switching on enum class in C++ 0x - Stack Overflow
    Many thanks,
    Jonathan.
    $ cat test.cpp
    #include <iostream>
    enum class Ternary { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
    int main( void )
       Ternary foo;
       switch ( foo ) {
          case Ternary::KnownTrue:
          case Ternary::KnownFalse:
          case Ternary::Unknown:
             std::cout << "Success\n";
    $ clang++ -std=c++11 test.cpp
    $ g++ -std=c++11 test.cpp
    $ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -std=c++11 test.cpp
    "test.cpp", line 8: Error: Cannot use Ternary to initialize integral type.
    "test.cpp", line 8: Error: Switch selection expression must be of an integral type.
    "test.cpp", line 9: Error: An integer constant expression is required for a case label.
    "test.cpp", line 10: Error: An integer constant expression is required for a case label.
    "test.cpp", line 11: Error: An integer constant expression is required for a case label.
    5 Error(s) detected.

    Thanks for reporting this problem! I have filed bug 18499900.
    BTW, according to the C++11 standard, the code is actually not valid. Section 6.4.2, switch statement, says an implicit conversion to an integral type is required, which is not the case for for a scoped enum (one using the "class enum" syntax). This limitation was raised in the C++ Committee as an issue to be fixed, and the C++14 standard makes the code valid.
    As a workaround, or to make the code conform to C++11, you can add casts to int for the enum variable and the enumerators.
    Message was edited by: Steve_Clamage

  • Using enum's from one class in another?

    heya,
    I have two classes, Predator and Simulation, and Predator has an public enum 'target' inside it.
    Simulation needs to use a switch statement based on target (Simulation contains a list of Predators, and I'm returning type target to Simulation), but I am getting errors when compiling the two classes from the commandline (for some weird reason, it works fine in Eclipse - both classes are in a package 'lepidoptera', which I originally thoguht was the issue).
    Errors are like (5 of these):
    Simulation.java:64: an enum switch case label must be the unqualified name of an enumeration constant
                    case (mimic):Any ideas?
    Thanks,
    Victor

    This works for moi:
    public class Predator {
        public enum Target {SEITAN, TOFU, TEMPEH}
    public class Simulation {
        public static String f(Predator.Target target) {
            switch(target) {
                case SEITAN:
                    return "yuck";
                case TOFU:
                    return "ugh";
                case TEMPEH:
                    return "crikey";
                default:
                    return "nuts";
        public static void main(String[] args) {
            System.out.println(f(Predator.Target.SEITAN));
            System.out.println(f(Predator.Target.TOFU));
            System.out.println(f(Predator.Target.TEMPEH));
    }And do you know that an enum can be a top level class? In other
    words, that you can create the one-line file Target.java:
    public enum Target {SEITAN, TOFU, TEMPEH}

Maybe you are looking for