11 Replies Latest reply: Sep 15, 2009 12:24 PM by 782681 RSS

    convert short to an enum

    613272
      I have a value stored in a 'short' and I want to convert it to a corresponding enum that I have defined

      short it =3;


      Thanks
        • 1. Re: convert short to an enum
          masijade
          Doug_99 wrote:
          I have a value stored in a 'short' and I want to convert it to a corresponding enum that I have defined

          short it =3;


          Thanks
          It might help to see your enum, but enums do have a built in valueOf method.
          • 2. Re: convert short to an enum
            613272
            private enum Values{

            ZERO,
            ONE,
            TWO

            }

            short it = 2;

            If I try
            Values.valueOf() this only accepts strings

            Do I need to do

            Values.valueOf(it.toString);
            • 3. Re: convert short to an enum
              796440
              masijade. wrote:
              Doug_99 wrote:
              I have a value stored in a 'short' and I want to convert it to a corresponding enum that I have defined

              short it =3;


              Thanks
              It might help to see your enum, but enums do have a built in valueOf method.
              Good luck getting something back for valueOf("3");
              • 4. Re: convert short to an enum
                796440
                Doug_99 wrote:
                private enum Values{

                ZERO,
                ONE,
                TWO

                }

                short it = 2;

                If I try
                Values.valueOf() this only accepts strings

                Do I need to do

                Values.valueOf(it.toString);
                Values.values()[2];
                • 5. Re: convert short to an enum
                  masijade
                  jverd wrote:
                  Good luck getting something back for valueOf("3");
                  True. Doesn't hurt to point out that it exists, though. ;-)

                  Of course, if the enum is setup right, you can (although not with "3" and not with the built-in valueOf). ;-)
                  public class Main {
                  
                      public enum Test {
                          ZERO ((short) 0),
                          ONE ((short) 1),
                          TWO ((short) 2);
                  
                          private final short value;
                          Test(short value) {
                              this.value = value;
                          }
                  
                          public static Test valueOf(short value) {
                              return values()[value];
                              // or
                              //for (Test t : values()) {
                              //    if (t.value == value) {
                              //        return t;
                              //    }
                              //return null;
                          }
                      }
                  
                      public static void main(String[] args) throws Exception {
                          System.out.println(Test.valueOf((short) 1));
                          System.out.println(Test.valueOf("ONE"));
                      }
                  }
                  • 6. Re: convert short to an enum
                    796440
                    masijade. wrote:
                    jverd wrote:
                    Good luck getting something back for valueOf("3");
                    True. Doesn't hurt to point out that it exists, though. ;-)

                    Of course, if the enum is setup right, you can (although not with "3" and not with the built-in valueOf). ;-)
                    public class Main {
                    
                    public enum Test {
                    ZERO ((short) 0),
                    ONE ((short) 1),
                    TWO ((short) 2);
                    
                    private final short value;
                    Test(short value) {
                    this.value = value;
                    }
                    
                    public static Test valueOf(short value) {
                    return values()[value];
                    // or
                    //for (Test t : values()) {
                    //    if (t.value == value) {
                    //        return t;
                    //    }
                    //return null;
                    }
                    }
                    
                    public static void main(String[] args) throws Exception {
                    System.out.println(Test.valueOf((short) 1));
                    System.out.println(Test.valueOf("ONE"));
                    }
                    }
                    Okay, you've lost me. I'm not sure what you're trying to show here. The value member isn't used at all, and the valueOf method is just a wrapper around the values()[x] approach that I mentioned earlier.
                    • 7. Re: convert short to an enum
                      masijade
                      jverd wrote:
                      Okay, you've lost me. I'm not sure what you're trying to show here. The value member isn't used at all, and the valueOf method is just a wrapper around the values()[x] approach that I mentioned earlier.
                      That you can use a valueOf type approach with a short without the calling class needing to know what the values array looks like. And, if you notice, there is another approach sited in the method.

                      Edit: The enum is not complete, BTW. It's just a minor example. There should definately be "getValue" type method, as well, for retreiving the actual value. It was, as already pointed out, just a demonstration that you can use a valueOf type approach.
                      • 8. Re: convert short to an enum
                        796440
                        masijade. wrote:
                        jverd wrote:
                        Okay, you've lost me. I'm not sure what you're trying to show here. The value member isn't used at all, and the valueOf method is just a wrapper around the values()[x] approach that I mentioned earlier.
                        That you can use a valueOf type approach with a short without the calling class needing to know what the values array looks like.
                        Ah, I see.

                        I humbly suggest that that examle would be better off without the misleading value member variable. :-)
                        • 9. Re: convert short to an enum
                          807580
                          Doug_99 wrote:
                          I have a value stored in a 'short' and I want to convert it to a corresponding enum that I have defined

                          short it =3;
                          The thing is, you have to define what you mean by "corresponding". If the value has the qualities of a number; sequence, arithmetic etc. then you probably shouldn't be using an enum in the first place.

                          Enum values do have an "ordinal" attribute, i.e. they get numbered sequentially when created. This is what the values()[ordinal] approach will give you. But if you're using it then you probably aren't using enums for what they are good at.

                          To define your own correspondence simply create an initialized array of enum values e.g.
                          private static final MyEnum[] numberToEnum = new MyEnum[] {
                               MyEnum.ONE, MyEnum.TWO,...
                          };
                          The converse would be an initialized EnumMap<MyEnum, Short>
                          • 10. Re: convert short to an enum
                            807580
                            malcolmmc wrote:
                            private static final MyEnum[] numberToEnum = new MyEnum[] {
                            MyEnum.ONE, MyEnum.TWO,...
                            };
                            The converse would be an initialized EnumMap<MyEnum, Short>
                            I agree with Malcom. I find that most of the time when people do this it's to facilitate serialization, especially when transmitting a message to another code set or application. If you're just going to send a short to represent the enum, using the enum's ordinal isn't necessarily a good idea because code changes to the enum later on (inserting/removing a value) will create class incompatibilities, etc.

                            I would suggest either doing both of those things that Malcom said, or use a bidirectional map of some kind.

                            Or, if it makes sense for the circumstances, roll it all up in the enum itself. This is an example where the (integer) code and enum type are very tightly coupled and standardized:
                            enum HTTPStatus {
                                OK (200),
                                BAD_REQUEST(400),
                                NOT_FOUND(404) 
                                ;
                                
                                private static Map<Integer, HTTPStatus> codeMap = 
                                 new HashMap<Integer, HTTPStatus>();
                                
                                static {
                                 for ( HTTPStatus status : HTTPStatus.values() ) {
                                     codeMap.put(status.getCode(), status);
                                 }
                                }
                            
                                private final int code;
                            
                                private HTTPStatus(int code)
                                {
                                 this.code = code;
                                }
                            
                                public int getCode()
                                {
                                    return code;
                                }
                            
                                public static HTTPStatus forCode(int code) {
                                 return codeMap.get(code);
                                }
                            }
                            One thing that I learned in that example is that enums, contrary to classes, do all of their instance initialization before any static initialization is performed. In other words, I couldn't add to forIntegerMap from the constructor, and had to use a static initializer block instead. Never knew that before now. It's logical though.

                            Edited by: endasil on 15-Sep-2009 11:03 AM
                            • 11. enums instance initialization
                              782681
                              endasil wrote:
                              ...One thing that I learned in that example is that enums, contrary to classes, do all of their instance initialization before any static initialization is performed. In other words, I couldn't add to forIntegerMap from the constructor, and had to use a static initializer block instead. Never knew that before now. It's logical though.
                              Above seems to be one of (many:) reasons why [Joshua "Effective Java" Bloch|http://www.ddj.com/java/208403883?pgno=3|Creating and Destroying Java Objects: Part 1] promotes enum as the best way to implement a singleton:
                              ...Simply make an enum type with one element:
                                  // Enum singleton - the preferred approach
                              public enum Elvis {
                              INSTANCE;
                              public void leaveTheBuilding() { ... }
                              } 
                              This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton...
                              :)