How to convert enum value to int?












205















I have a function which return a type int. However, I only have a value of the TAX enumeration.



How can I cast the TAX enumeration value to an int?



public enum TAX {
NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);

private int value;
private TAX(int value){
this.value = value;
}
}

TAX var = TAX.NOTAX; // This value will differ

public int getTaxValue()
{
// what do do here?
// return (int)var;
}









share|improve this question




















  • 1





    Possible duplicate of How to match int to enum

    – malat
    Nov 18 '16 at 13:38
















205















I have a function which return a type int. However, I only have a value of the TAX enumeration.



How can I cast the TAX enumeration value to an int?



public enum TAX {
NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);

private int value;
private TAX(int value){
this.value = value;
}
}

TAX var = TAX.NOTAX; // This value will differ

public int getTaxValue()
{
// what do do here?
// return (int)var;
}









share|improve this question




















  • 1





    Possible duplicate of How to match int to enum

    – malat
    Nov 18 '16 at 13:38














205












205








205


36






I have a function which return a type int. However, I only have a value of the TAX enumeration.



How can I cast the TAX enumeration value to an int?



public enum TAX {
NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);

private int value;
private TAX(int value){
this.value = value;
}
}

TAX var = TAX.NOTAX; // This value will differ

public int getTaxValue()
{
// what do do here?
// return (int)var;
}









share|improve this question
















I have a function which return a type int. However, I only have a value of the TAX enumeration.



How can I cast the TAX enumeration value to an int?



public enum TAX {
NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);

private int value;
private TAX(int value){
this.value = value;
}
}

TAX var = TAX.NOTAX; // This value will differ

public int getTaxValue()
{
// what do do here?
// return (int)var;
}






java enums






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '11 at 19:53







user166390

















asked Nov 16 '11 at 19:50









vrbilgivrbilgi

2,423103051




2,423103051








  • 1





    Possible duplicate of How to match int to enum

    – malat
    Nov 18 '16 at 13:38














  • 1





    Possible duplicate of How to match int to enum

    – malat
    Nov 18 '16 at 13:38








1




1





Possible duplicate of How to match int to enum

– malat
Nov 18 '16 at 13:38





Possible duplicate of How to match int to enum

– malat
Nov 18 '16 at 13:38












6 Answers
6






active

oldest

votes


















311














You'd need to make the enum expose value somehow, e.g.



public enum Tax {
NONE(0), SALES(10), IMPORT(5);

private final int value;
private Tax(int value) {
this.value = value;
}

public int getValue() {
return value;
}
}

...

public int getTaxValue() {
Tax tax = Tax.NONE; // Or whatever
return tax.getValue();
}


(I've changed the names to be a bit more conventional and readable, btw.)



This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.






share|improve this answer



















  • 11





    there is a better idea here stackoverflow.com/a/7996473/398348

    – likejudo
    Sep 10 '14 at 21:44








  • 1





    @likejiujitsu: That's going in the opposite direction. In this question, the OP already has a value of type Tax, and wants to get the numeric value from it.

    – Jon Skeet
    Sep 10 '14 at 22:34











  • I just tried it and realize it fails myEnumValue = MyEnum.valueOf(myInt); the arg has to be of type String - or is there something I am missing?

    – likejudo
    Sep 10 '14 at 22:58






  • 6





    @likejiujitsu: Well it's irrelevant to this question...

    – Jon Skeet
    Sep 11 '14 at 0:13











  • This solution is worse than nothing. Seems enums in Java just shouldn't be used? Or has JDK 1.8 changed that?

    – ebyrob
    Nov 11 '16 at 16:10



















187














I prefer this:



public enum Color {

White,

Green,

Blue,

Purple,

Orange,

Red
}


then:



//cast enum to int
int color = Color.Blue.ordinal();





share|improve this answer



















  • 30





    This is incorrect/not recommended by Joshua Bloch in his book Effective Java (2nd ed). See item 31.

    – user504342
    Oct 13 '13 at 13:49






  • 34





    @user504342 I do not have the 2nd edition of the book so can you please give us the gist of why it is not recommended?

    – likejudo
    Sep 10 '14 at 20:25






  • 14





    2 reasons: one, any association between the ordinal values and the constants will break if new constants are added, and two the API docs specifically recommend against it.

    – jordanpg
    Oct 28 '14 at 3:26






  • 6





    So clean and perfect. I see a few "don't do it" and "not recommended". I'll have to research on why it's considered bad. Some of the bloated samples look bad IMO. So much work to do such a simple task.

    – Herb Meehan
    May 20 '16 at 18:38






  • 3





    In a team, you're pretty sure on of your co-developer will add a value in the middle (worse at the beginning), or just sort them because they have nothing to do and completely mess the code using .ordinal()

    – Michael Laffargue
    May 3 '17 at 13:47



















17














If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.



If you want a unique number that represent the enum value, you can use ordinal().






share|improve this answer



















  • 2





    Be careful. There are many more developmental anti-patterns that rely on ordinal() than valid use cases for ordinal(). If you need to store a unique value for the enum, then just store the enum. There are EnumSets, Lists of Enums, EnumMaps, and nearly any other Enum collection you might want available.

    – Edwin Buck
    Nov 16 '11 at 19:57






  • 1





    @EdwinBuck: That is good to point out, I just wanted to mention the existence of ordinal() because the OP didn't make it clear what he wanted the int to actually be.

    – unholysampler
    Nov 16 '11 at 20:01











  • Don't get ordinal. Please check the enum api regarding this. Up-vote removed.

    – Hovercraft Full Of Eels
    Nov 16 '11 at 20:22






  • 3





    I wonder what peoples' thoughts are about the use of ordinal() internally within the enum itself. For example, say I have an enum called "Season" which contains the values Spring, Summer, Autumn, and Winter, and it has a public method called next() which returns values()[(ordinal() + 1) % 4] Externally, no code ever sees the ordinal number, and there will never be additional members in this enum, so it seems like a valid use-case.

    – Darrel Hoffman
    Oct 29 '13 at 19:52






  • 1





    @DarrelHoffman My feeling is that doing that is fine, since the only strong arguments I see against using ordinal() hinge on far flung code being broken by changes to the enum enumeration constants. If you're going to modify the enum's constants you'd have to be in that file already. Most enums are fairly short, and if it's not you should be checking the file more thoroughly anyway. In both cases you should probably have a unit test covering your next() method anyway.

    – Alan Hensley
    Jun 1 '16 at 16:26





















11














Sometime some C# approach makes the life easier in Java world..:



class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;





share|improve this answer
























  • For me this is the most desirable way to go. I get the benefits of enum (code clarity), a data type that is DB friendly, and I don't have to research 100 enum alternatives to do it the "android way". Simple and effective.

    – John Ward
    Mar 1 '17 at 15:08











  • Nice. It's as if the java enum is just completely disconnected from the reality of what an enum is used for... especially if people then start abusing it for things like singletons. This approach does have the disadvantage it doesn't have an easy way to get all values though.

    – Nyerguds
    Sep 18 '18 at 9:01











  • Doesn't this have the disadvantage of trying to pass an enum value to a method? You can no longer pass a XLINK to a method, because it doesn't represent anything concrete. You lose the typing into your method. The method signature would have to read short instead of XLINK.

    – Dustin Jensen
    Dec 20 '18 at 4:03



















2














Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):



ValueType expected = ValueType.FLOAT;
String value = expected.name();

System.out.println("Name value: " + value);

ValueType actual = ValueType.valueOf(value);

if(expected.equals(actual)) System.out.println("Values are equal");





share|improve this answer































    0














    public enum Tax {

    NONE(1), SALES(2), IMPORT(3);

    private final int value;
    private Tax(int value) {
    this.value = value;
    }

    public String toString() {
    return Integer.toString(value);
    }
    }

    class Test {
    System.out.println(Tax.NONE); //Just an example.
    }





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8157755%2fhow-to-convert-enum-value-to-int%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      311














      You'd need to make the enum expose value somehow, e.g.



      public enum Tax {
      NONE(0), SALES(10), IMPORT(5);

      private final int value;
      private Tax(int value) {
      this.value = value;
      }

      public int getValue() {
      return value;
      }
      }

      ...

      public int getTaxValue() {
      Tax tax = Tax.NONE; // Or whatever
      return tax.getValue();
      }


      (I've changed the names to be a bit more conventional and readable, btw.)



      This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.






      share|improve this answer



















      • 11





        there is a better idea here stackoverflow.com/a/7996473/398348

        – likejudo
        Sep 10 '14 at 21:44








      • 1





        @likejiujitsu: That's going in the opposite direction. In this question, the OP already has a value of type Tax, and wants to get the numeric value from it.

        – Jon Skeet
        Sep 10 '14 at 22:34











      • I just tried it and realize it fails myEnumValue = MyEnum.valueOf(myInt); the arg has to be of type String - or is there something I am missing?

        – likejudo
        Sep 10 '14 at 22:58






      • 6





        @likejiujitsu: Well it's irrelevant to this question...

        – Jon Skeet
        Sep 11 '14 at 0:13











      • This solution is worse than nothing. Seems enums in Java just shouldn't be used? Or has JDK 1.8 changed that?

        – ebyrob
        Nov 11 '16 at 16:10
















      311














      You'd need to make the enum expose value somehow, e.g.



      public enum Tax {
      NONE(0), SALES(10), IMPORT(5);

      private final int value;
      private Tax(int value) {
      this.value = value;
      }

      public int getValue() {
      return value;
      }
      }

      ...

      public int getTaxValue() {
      Tax tax = Tax.NONE; // Or whatever
      return tax.getValue();
      }


      (I've changed the names to be a bit more conventional and readable, btw.)



      This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.






      share|improve this answer



















      • 11





        there is a better idea here stackoverflow.com/a/7996473/398348

        – likejudo
        Sep 10 '14 at 21:44








      • 1





        @likejiujitsu: That's going in the opposite direction. In this question, the OP already has a value of type Tax, and wants to get the numeric value from it.

        – Jon Skeet
        Sep 10 '14 at 22:34











      • I just tried it and realize it fails myEnumValue = MyEnum.valueOf(myInt); the arg has to be of type String - or is there something I am missing?

        – likejudo
        Sep 10 '14 at 22:58






      • 6





        @likejiujitsu: Well it's irrelevant to this question...

        – Jon Skeet
        Sep 11 '14 at 0:13











      • This solution is worse than nothing. Seems enums in Java just shouldn't be used? Or has JDK 1.8 changed that?

        – ebyrob
        Nov 11 '16 at 16:10














      311












      311








      311







      You'd need to make the enum expose value somehow, e.g.



      public enum Tax {
      NONE(0), SALES(10), IMPORT(5);

      private final int value;
      private Tax(int value) {
      this.value = value;
      }

      public int getValue() {
      return value;
      }
      }

      ...

      public int getTaxValue() {
      Tax tax = Tax.NONE; // Or whatever
      return tax.getValue();
      }


      (I've changed the names to be a bit more conventional and readable, btw.)



      This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.






      share|improve this answer













      You'd need to make the enum expose value somehow, e.g.



      public enum Tax {
      NONE(0), SALES(10), IMPORT(5);

      private final int value;
      private Tax(int value) {
      this.value = value;
      }

      public int getValue() {
      return value;
      }
      }

      ...

      public int getTaxValue() {
      Tax tax = Tax.NONE; // Or whatever
      return tax.getValue();
      }


      (I've changed the names to be a bit more conventional and readable, btw.)



      This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 16 '11 at 19:54









      Jon SkeetJon Skeet

      1089k69079488444




      1089k69079488444








      • 11





        there is a better idea here stackoverflow.com/a/7996473/398348

        – likejudo
        Sep 10 '14 at 21:44








      • 1





        @likejiujitsu: That's going in the opposite direction. In this question, the OP already has a value of type Tax, and wants to get the numeric value from it.

        – Jon Skeet
        Sep 10 '14 at 22:34











      • I just tried it and realize it fails myEnumValue = MyEnum.valueOf(myInt); the arg has to be of type String - or is there something I am missing?

        – likejudo
        Sep 10 '14 at 22:58






      • 6





        @likejiujitsu: Well it's irrelevant to this question...

        – Jon Skeet
        Sep 11 '14 at 0:13











      • This solution is worse than nothing. Seems enums in Java just shouldn't be used? Or has JDK 1.8 changed that?

        – ebyrob
        Nov 11 '16 at 16:10














      • 11





        there is a better idea here stackoverflow.com/a/7996473/398348

        – likejudo
        Sep 10 '14 at 21:44








      • 1





        @likejiujitsu: That's going in the opposite direction. In this question, the OP already has a value of type Tax, and wants to get the numeric value from it.

        – Jon Skeet
        Sep 10 '14 at 22:34











      • I just tried it and realize it fails myEnumValue = MyEnum.valueOf(myInt); the arg has to be of type String - or is there something I am missing?

        – likejudo
        Sep 10 '14 at 22:58






      • 6





        @likejiujitsu: Well it's irrelevant to this question...

        – Jon Skeet
        Sep 11 '14 at 0:13











      • This solution is worse than nothing. Seems enums in Java just shouldn't be used? Or has JDK 1.8 changed that?

        – ebyrob
        Nov 11 '16 at 16:10








      11




      11





      there is a better idea here stackoverflow.com/a/7996473/398348

      – likejudo
      Sep 10 '14 at 21:44







      there is a better idea here stackoverflow.com/a/7996473/398348

      – likejudo
      Sep 10 '14 at 21:44






      1




      1





      @likejiujitsu: That's going in the opposite direction. In this question, the OP already has a value of type Tax, and wants to get the numeric value from it.

      – Jon Skeet
      Sep 10 '14 at 22:34





      @likejiujitsu: That's going in the opposite direction. In this question, the OP already has a value of type Tax, and wants to get the numeric value from it.

      – Jon Skeet
      Sep 10 '14 at 22:34













      I just tried it and realize it fails myEnumValue = MyEnum.valueOf(myInt); the arg has to be of type String - or is there something I am missing?

      – likejudo
      Sep 10 '14 at 22:58





      I just tried it and realize it fails myEnumValue = MyEnum.valueOf(myInt); the arg has to be of type String - or is there something I am missing?

      – likejudo
      Sep 10 '14 at 22:58




      6




      6





      @likejiujitsu: Well it's irrelevant to this question...

      – Jon Skeet
      Sep 11 '14 at 0:13





      @likejiujitsu: Well it's irrelevant to this question...

      – Jon Skeet
      Sep 11 '14 at 0:13













      This solution is worse than nothing. Seems enums in Java just shouldn't be used? Or has JDK 1.8 changed that?

      – ebyrob
      Nov 11 '16 at 16:10





      This solution is worse than nothing. Seems enums in Java just shouldn't be used? Or has JDK 1.8 changed that?

      – ebyrob
      Nov 11 '16 at 16:10













      187














      I prefer this:



      public enum Color {

      White,

      Green,

      Blue,

      Purple,

      Orange,

      Red
      }


      then:



      //cast enum to int
      int color = Color.Blue.ordinal();





      share|improve this answer



















      • 30





        This is incorrect/not recommended by Joshua Bloch in his book Effective Java (2nd ed). See item 31.

        – user504342
        Oct 13 '13 at 13:49






      • 34





        @user504342 I do not have the 2nd edition of the book so can you please give us the gist of why it is not recommended?

        – likejudo
        Sep 10 '14 at 20:25






      • 14





        2 reasons: one, any association between the ordinal values and the constants will break if new constants are added, and two the API docs specifically recommend against it.

        – jordanpg
        Oct 28 '14 at 3:26






      • 6





        So clean and perfect. I see a few "don't do it" and "not recommended". I'll have to research on why it's considered bad. Some of the bloated samples look bad IMO. So much work to do such a simple task.

        – Herb Meehan
        May 20 '16 at 18:38






      • 3





        In a team, you're pretty sure on of your co-developer will add a value in the middle (worse at the beginning), or just sort them because they have nothing to do and completely mess the code using .ordinal()

        – Michael Laffargue
        May 3 '17 at 13:47
















      187














      I prefer this:



      public enum Color {

      White,

      Green,

      Blue,

      Purple,

      Orange,

      Red
      }


      then:



      //cast enum to int
      int color = Color.Blue.ordinal();





      share|improve this answer



















      • 30





        This is incorrect/not recommended by Joshua Bloch in his book Effective Java (2nd ed). See item 31.

        – user504342
        Oct 13 '13 at 13:49






      • 34





        @user504342 I do not have the 2nd edition of the book so can you please give us the gist of why it is not recommended?

        – likejudo
        Sep 10 '14 at 20:25






      • 14





        2 reasons: one, any association between the ordinal values and the constants will break if new constants are added, and two the API docs specifically recommend against it.

        – jordanpg
        Oct 28 '14 at 3:26






      • 6





        So clean and perfect. I see a few "don't do it" and "not recommended". I'll have to research on why it's considered bad. Some of the bloated samples look bad IMO. So much work to do such a simple task.

        – Herb Meehan
        May 20 '16 at 18:38






      • 3





        In a team, you're pretty sure on of your co-developer will add a value in the middle (worse at the beginning), or just sort them because they have nothing to do and completely mess the code using .ordinal()

        – Michael Laffargue
        May 3 '17 at 13:47














      187












      187








      187







      I prefer this:



      public enum Color {

      White,

      Green,

      Blue,

      Purple,

      Orange,

      Red
      }


      then:



      //cast enum to int
      int color = Color.Blue.ordinal();





      share|improve this answer













      I prefer this:



      public enum Color {

      White,

      Green,

      Blue,

      Purple,

      Orange,

      Red
      }


      then:



      //cast enum to int
      int color = Color.Blue.ordinal();






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Apr 11 '13 at 3:06









      viviavivia

      2,108197




      2,108197








      • 30





        This is incorrect/not recommended by Joshua Bloch in his book Effective Java (2nd ed). See item 31.

        – user504342
        Oct 13 '13 at 13:49






      • 34





        @user504342 I do not have the 2nd edition of the book so can you please give us the gist of why it is not recommended?

        – likejudo
        Sep 10 '14 at 20:25






      • 14





        2 reasons: one, any association between the ordinal values and the constants will break if new constants are added, and two the API docs specifically recommend against it.

        – jordanpg
        Oct 28 '14 at 3:26






      • 6





        So clean and perfect. I see a few "don't do it" and "not recommended". I'll have to research on why it's considered bad. Some of the bloated samples look bad IMO. So much work to do such a simple task.

        – Herb Meehan
        May 20 '16 at 18:38






      • 3





        In a team, you're pretty sure on of your co-developer will add a value in the middle (worse at the beginning), or just sort them because they have nothing to do and completely mess the code using .ordinal()

        – Michael Laffargue
        May 3 '17 at 13:47














      • 30





        This is incorrect/not recommended by Joshua Bloch in his book Effective Java (2nd ed). See item 31.

        – user504342
        Oct 13 '13 at 13:49






      • 34





        @user504342 I do not have the 2nd edition of the book so can you please give us the gist of why it is not recommended?

        – likejudo
        Sep 10 '14 at 20:25






      • 14





        2 reasons: one, any association between the ordinal values and the constants will break if new constants are added, and two the API docs specifically recommend against it.

        – jordanpg
        Oct 28 '14 at 3:26






      • 6





        So clean and perfect. I see a few "don't do it" and "not recommended". I'll have to research on why it's considered bad. Some of the bloated samples look bad IMO. So much work to do such a simple task.

        – Herb Meehan
        May 20 '16 at 18:38






      • 3





        In a team, you're pretty sure on of your co-developer will add a value in the middle (worse at the beginning), or just sort them because they have nothing to do and completely mess the code using .ordinal()

        – Michael Laffargue
        May 3 '17 at 13:47








      30




      30





      This is incorrect/not recommended by Joshua Bloch in his book Effective Java (2nd ed). See item 31.

      – user504342
      Oct 13 '13 at 13:49





      This is incorrect/not recommended by Joshua Bloch in his book Effective Java (2nd ed). See item 31.

      – user504342
      Oct 13 '13 at 13:49




      34




      34





      @user504342 I do not have the 2nd edition of the book so can you please give us the gist of why it is not recommended?

      – likejudo
      Sep 10 '14 at 20:25





      @user504342 I do not have the 2nd edition of the book so can you please give us the gist of why it is not recommended?

      – likejudo
      Sep 10 '14 at 20:25




      14




      14





      2 reasons: one, any association between the ordinal values and the constants will break if new constants are added, and two the API docs specifically recommend against it.

      – jordanpg
      Oct 28 '14 at 3:26





      2 reasons: one, any association between the ordinal values and the constants will break if new constants are added, and two the API docs specifically recommend against it.

      – jordanpg
      Oct 28 '14 at 3:26




      6




      6





      So clean and perfect. I see a few "don't do it" and "not recommended". I'll have to research on why it's considered bad. Some of the bloated samples look bad IMO. So much work to do such a simple task.

      – Herb Meehan
      May 20 '16 at 18:38





      So clean and perfect. I see a few "don't do it" and "not recommended". I'll have to research on why it's considered bad. Some of the bloated samples look bad IMO. So much work to do such a simple task.

      – Herb Meehan
      May 20 '16 at 18:38




      3




      3





      In a team, you're pretty sure on of your co-developer will add a value in the middle (worse at the beginning), or just sort them because they have nothing to do and completely mess the code using .ordinal()

      – Michael Laffargue
      May 3 '17 at 13:47





      In a team, you're pretty sure on of your co-developer will add a value in the middle (worse at the beginning), or just sort them because they have nothing to do and completely mess the code using .ordinal()

      – Michael Laffargue
      May 3 '17 at 13:47











      17














      If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.



      If you want a unique number that represent the enum value, you can use ordinal().






      share|improve this answer



















      • 2





        Be careful. There are many more developmental anti-patterns that rely on ordinal() than valid use cases for ordinal(). If you need to store a unique value for the enum, then just store the enum. There are EnumSets, Lists of Enums, EnumMaps, and nearly any other Enum collection you might want available.

        – Edwin Buck
        Nov 16 '11 at 19:57






      • 1





        @EdwinBuck: That is good to point out, I just wanted to mention the existence of ordinal() because the OP didn't make it clear what he wanted the int to actually be.

        – unholysampler
        Nov 16 '11 at 20:01











      • Don't get ordinal. Please check the enum api regarding this. Up-vote removed.

        – Hovercraft Full Of Eels
        Nov 16 '11 at 20:22






      • 3





        I wonder what peoples' thoughts are about the use of ordinal() internally within the enum itself. For example, say I have an enum called "Season" which contains the values Spring, Summer, Autumn, and Winter, and it has a public method called next() which returns values()[(ordinal() + 1) % 4] Externally, no code ever sees the ordinal number, and there will never be additional members in this enum, so it seems like a valid use-case.

        – Darrel Hoffman
        Oct 29 '13 at 19:52






      • 1





        @DarrelHoffman My feeling is that doing that is fine, since the only strong arguments I see against using ordinal() hinge on far flung code being broken by changes to the enum enumeration constants. If you're going to modify the enum's constants you'd have to be in that file already. Most enums are fairly short, and if it's not you should be checking the file more thoroughly anyway. In both cases you should probably have a unit test covering your next() method anyway.

        – Alan Hensley
        Jun 1 '16 at 16:26


















      17














      If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.



      If you want a unique number that represent the enum value, you can use ordinal().






      share|improve this answer



















      • 2





        Be careful. There are many more developmental anti-patterns that rely on ordinal() than valid use cases for ordinal(). If you need to store a unique value for the enum, then just store the enum. There are EnumSets, Lists of Enums, EnumMaps, and nearly any other Enum collection you might want available.

        – Edwin Buck
        Nov 16 '11 at 19:57






      • 1





        @EdwinBuck: That is good to point out, I just wanted to mention the existence of ordinal() because the OP didn't make it clear what he wanted the int to actually be.

        – unholysampler
        Nov 16 '11 at 20:01











      • Don't get ordinal. Please check the enum api regarding this. Up-vote removed.

        – Hovercraft Full Of Eels
        Nov 16 '11 at 20:22






      • 3





        I wonder what peoples' thoughts are about the use of ordinal() internally within the enum itself. For example, say I have an enum called "Season" which contains the values Spring, Summer, Autumn, and Winter, and it has a public method called next() which returns values()[(ordinal() + 1) % 4] Externally, no code ever sees the ordinal number, and there will never be additional members in this enum, so it seems like a valid use-case.

        – Darrel Hoffman
        Oct 29 '13 at 19:52






      • 1





        @DarrelHoffman My feeling is that doing that is fine, since the only strong arguments I see against using ordinal() hinge on far flung code being broken by changes to the enum enumeration constants. If you're going to modify the enum's constants you'd have to be in that file already. Most enums are fairly short, and if it's not you should be checking the file more thoroughly anyway. In both cases you should probably have a unit test covering your next() method anyway.

        – Alan Hensley
        Jun 1 '16 at 16:26
















      17












      17








      17







      If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.



      If you want a unique number that represent the enum value, you can use ordinal().






      share|improve this answer













      If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.



      If you want a unique number that represent the enum value, you can use ordinal().







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 16 '11 at 19:54









      unholysamplerunholysampler

      14k33662




      14k33662








      • 2





        Be careful. There are many more developmental anti-patterns that rely on ordinal() than valid use cases for ordinal(). If you need to store a unique value for the enum, then just store the enum. There are EnumSets, Lists of Enums, EnumMaps, and nearly any other Enum collection you might want available.

        – Edwin Buck
        Nov 16 '11 at 19:57






      • 1





        @EdwinBuck: That is good to point out, I just wanted to mention the existence of ordinal() because the OP didn't make it clear what he wanted the int to actually be.

        – unholysampler
        Nov 16 '11 at 20:01











      • Don't get ordinal. Please check the enum api regarding this. Up-vote removed.

        – Hovercraft Full Of Eels
        Nov 16 '11 at 20:22






      • 3





        I wonder what peoples' thoughts are about the use of ordinal() internally within the enum itself. For example, say I have an enum called "Season" which contains the values Spring, Summer, Autumn, and Winter, and it has a public method called next() which returns values()[(ordinal() + 1) % 4] Externally, no code ever sees the ordinal number, and there will never be additional members in this enum, so it seems like a valid use-case.

        – Darrel Hoffman
        Oct 29 '13 at 19:52






      • 1





        @DarrelHoffman My feeling is that doing that is fine, since the only strong arguments I see against using ordinal() hinge on far flung code being broken by changes to the enum enumeration constants. If you're going to modify the enum's constants you'd have to be in that file already. Most enums are fairly short, and if it's not you should be checking the file more thoroughly anyway. In both cases you should probably have a unit test covering your next() method anyway.

        – Alan Hensley
        Jun 1 '16 at 16:26
















      • 2





        Be careful. There are many more developmental anti-patterns that rely on ordinal() than valid use cases for ordinal(). If you need to store a unique value for the enum, then just store the enum. There are EnumSets, Lists of Enums, EnumMaps, and nearly any other Enum collection you might want available.

        – Edwin Buck
        Nov 16 '11 at 19:57






      • 1





        @EdwinBuck: That is good to point out, I just wanted to mention the existence of ordinal() because the OP didn't make it clear what he wanted the int to actually be.

        – unholysampler
        Nov 16 '11 at 20:01











      • Don't get ordinal. Please check the enum api regarding this. Up-vote removed.

        – Hovercraft Full Of Eels
        Nov 16 '11 at 20:22






      • 3





        I wonder what peoples' thoughts are about the use of ordinal() internally within the enum itself. For example, say I have an enum called "Season" which contains the values Spring, Summer, Autumn, and Winter, and it has a public method called next() which returns values()[(ordinal() + 1) % 4] Externally, no code ever sees the ordinal number, and there will never be additional members in this enum, so it seems like a valid use-case.

        – Darrel Hoffman
        Oct 29 '13 at 19:52






      • 1





        @DarrelHoffman My feeling is that doing that is fine, since the only strong arguments I see against using ordinal() hinge on far flung code being broken by changes to the enum enumeration constants. If you're going to modify the enum's constants you'd have to be in that file already. Most enums are fairly short, and if it's not you should be checking the file more thoroughly anyway. In both cases you should probably have a unit test covering your next() method anyway.

        – Alan Hensley
        Jun 1 '16 at 16:26










      2




      2





      Be careful. There are many more developmental anti-patterns that rely on ordinal() than valid use cases for ordinal(). If you need to store a unique value for the enum, then just store the enum. There are EnumSets, Lists of Enums, EnumMaps, and nearly any other Enum collection you might want available.

      – Edwin Buck
      Nov 16 '11 at 19:57





      Be careful. There are many more developmental anti-patterns that rely on ordinal() than valid use cases for ordinal(). If you need to store a unique value for the enum, then just store the enum. There are EnumSets, Lists of Enums, EnumMaps, and nearly any other Enum collection you might want available.

      – Edwin Buck
      Nov 16 '11 at 19:57




      1




      1





      @EdwinBuck: That is good to point out, I just wanted to mention the existence of ordinal() because the OP didn't make it clear what he wanted the int to actually be.

      – unholysampler
      Nov 16 '11 at 20:01





      @EdwinBuck: That is good to point out, I just wanted to mention the existence of ordinal() because the OP didn't make it clear what he wanted the int to actually be.

      – unholysampler
      Nov 16 '11 at 20:01













      Don't get ordinal. Please check the enum api regarding this. Up-vote removed.

      – Hovercraft Full Of Eels
      Nov 16 '11 at 20:22





      Don't get ordinal. Please check the enum api regarding this. Up-vote removed.

      – Hovercraft Full Of Eels
      Nov 16 '11 at 20:22




      3




      3





      I wonder what peoples' thoughts are about the use of ordinal() internally within the enum itself. For example, say I have an enum called "Season" which contains the values Spring, Summer, Autumn, and Winter, and it has a public method called next() which returns values()[(ordinal() + 1) % 4] Externally, no code ever sees the ordinal number, and there will never be additional members in this enum, so it seems like a valid use-case.

      – Darrel Hoffman
      Oct 29 '13 at 19:52





      I wonder what peoples' thoughts are about the use of ordinal() internally within the enum itself. For example, say I have an enum called "Season" which contains the values Spring, Summer, Autumn, and Winter, and it has a public method called next() which returns values()[(ordinal() + 1) % 4] Externally, no code ever sees the ordinal number, and there will never be additional members in this enum, so it seems like a valid use-case.

      – Darrel Hoffman
      Oct 29 '13 at 19:52




      1




      1





      @DarrelHoffman My feeling is that doing that is fine, since the only strong arguments I see against using ordinal() hinge on far flung code being broken by changes to the enum enumeration constants. If you're going to modify the enum's constants you'd have to be in that file already. Most enums are fairly short, and if it's not you should be checking the file more thoroughly anyway. In both cases you should probably have a unit test covering your next() method anyway.

      – Alan Hensley
      Jun 1 '16 at 16:26







      @DarrelHoffman My feeling is that doing that is fine, since the only strong arguments I see against using ordinal() hinge on far flung code being broken by changes to the enum enumeration constants. If you're going to modify the enum's constants you'd have to be in that file already. Most enums are fairly short, and if it's not you should be checking the file more thoroughly anyway. In both cases you should probably have a unit test covering your next() method anyway.

      – Alan Hensley
      Jun 1 '16 at 16:26













      11














      Sometime some C# approach makes the life easier in Java world..:



      class XLINK {
      static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
      }
      //Now is trivial to use it like a C# enum:
      int rcv = XLINK.ACK;





      share|improve this answer
























      • For me this is the most desirable way to go. I get the benefits of enum (code clarity), a data type that is DB friendly, and I don't have to research 100 enum alternatives to do it the "android way". Simple and effective.

        – John Ward
        Mar 1 '17 at 15:08











      • Nice. It's as if the java enum is just completely disconnected from the reality of what an enum is used for... especially if people then start abusing it for things like singletons. This approach does have the disadvantage it doesn't have an easy way to get all values though.

        – Nyerguds
        Sep 18 '18 at 9:01











      • Doesn't this have the disadvantage of trying to pass an enum value to a method? You can no longer pass a XLINK to a method, because it doesn't represent anything concrete. You lose the typing into your method. The method signature would have to read short instead of XLINK.

        – Dustin Jensen
        Dec 20 '18 at 4:03
















      11














      Sometime some C# approach makes the life easier in Java world..:



      class XLINK {
      static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
      }
      //Now is trivial to use it like a C# enum:
      int rcv = XLINK.ACK;





      share|improve this answer
























      • For me this is the most desirable way to go. I get the benefits of enum (code clarity), a data type that is DB friendly, and I don't have to research 100 enum alternatives to do it the "android way". Simple and effective.

        – John Ward
        Mar 1 '17 at 15:08











      • Nice. It's as if the java enum is just completely disconnected from the reality of what an enum is used for... especially if people then start abusing it for things like singletons. This approach does have the disadvantage it doesn't have an easy way to get all values though.

        – Nyerguds
        Sep 18 '18 at 9:01











      • Doesn't this have the disadvantage of trying to pass an enum value to a method? You can no longer pass a XLINK to a method, because it doesn't represent anything concrete. You lose the typing into your method. The method signature would have to read short instead of XLINK.

        – Dustin Jensen
        Dec 20 '18 at 4:03














      11












      11








      11







      Sometime some C# approach makes the life easier in Java world..:



      class XLINK {
      static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
      }
      //Now is trivial to use it like a C# enum:
      int rcv = XLINK.ACK;





      share|improve this answer













      Sometime some C# approach makes the life easier in Java world..:



      class XLINK {
      static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
      }
      //Now is trivial to use it like a C# enum:
      int rcv = XLINK.ACK;






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 10 '17 at 14:06









      VladiVladi

      18624




      18624













      • For me this is the most desirable way to go. I get the benefits of enum (code clarity), a data type that is DB friendly, and I don't have to research 100 enum alternatives to do it the "android way". Simple and effective.

        – John Ward
        Mar 1 '17 at 15:08











      • Nice. It's as if the java enum is just completely disconnected from the reality of what an enum is used for... especially if people then start abusing it for things like singletons. This approach does have the disadvantage it doesn't have an easy way to get all values though.

        – Nyerguds
        Sep 18 '18 at 9:01











      • Doesn't this have the disadvantage of trying to pass an enum value to a method? You can no longer pass a XLINK to a method, because it doesn't represent anything concrete. You lose the typing into your method. The method signature would have to read short instead of XLINK.

        – Dustin Jensen
        Dec 20 '18 at 4:03



















      • For me this is the most desirable way to go. I get the benefits of enum (code clarity), a data type that is DB friendly, and I don't have to research 100 enum alternatives to do it the "android way". Simple and effective.

        – John Ward
        Mar 1 '17 at 15:08











      • Nice. It's as if the java enum is just completely disconnected from the reality of what an enum is used for... especially if people then start abusing it for things like singletons. This approach does have the disadvantage it doesn't have an easy way to get all values though.

        – Nyerguds
        Sep 18 '18 at 9:01











      • Doesn't this have the disadvantage of trying to pass an enum value to a method? You can no longer pass a XLINK to a method, because it doesn't represent anything concrete. You lose the typing into your method. The method signature would have to read short instead of XLINK.

        – Dustin Jensen
        Dec 20 '18 at 4:03

















      For me this is the most desirable way to go. I get the benefits of enum (code clarity), a data type that is DB friendly, and I don't have to research 100 enum alternatives to do it the "android way". Simple and effective.

      – John Ward
      Mar 1 '17 at 15:08





      For me this is the most desirable way to go. I get the benefits of enum (code clarity), a data type that is DB friendly, and I don't have to research 100 enum alternatives to do it the "android way". Simple and effective.

      – John Ward
      Mar 1 '17 at 15:08













      Nice. It's as if the java enum is just completely disconnected from the reality of what an enum is used for... especially if people then start abusing it for things like singletons. This approach does have the disadvantage it doesn't have an easy way to get all values though.

      – Nyerguds
      Sep 18 '18 at 9:01





      Nice. It's as if the java enum is just completely disconnected from the reality of what an enum is used for... especially if people then start abusing it for things like singletons. This approach does have the disadvantage it doesn't have an easy way to get all values though.

      – Nyerguds
      Sep 18 '18 at 9:01













      Doesn't this have the disadvantage of trying to pass an enum value to a method? You can no longer pass a XLINK to a method, because it doesn't represent anything concrete. You lose the typing into your method. The method signature would have to read short instead of XLINK.

      – Dustin Jensen
      Dec 20 '18 at 4:03





      Doesn't this have the disadvantage of trying to pass an enum value to a method? You can no longer pass a XLINK to a method, because it doesn't represent anything concrete. You lose the typing into your method. The method signature would have to read short instead of XLINK.

      – Dustin Jensen
      Dec 20 '18 at 4:03











      2














      Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):



      ValueType expected = ValueType.FLOAT;
      String value = expected.name();

      System.out.println("Name value: " + value);

      ValueType actual = ValueType.valueOf(value);

      if(expected.equals(actual)) System.out.println("Values are equal");





      share|improve this answer




























        2














        Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):



        ValueType expected = ValueType.FLOAT;
        String value = expected.name();

        System.out.println("Name value: " + value);

        ValueType actual = ValueType.valueOf(value);

        if(expected.equals(actual)) System.out.println("Values are equal");





        share|improve this answer


























          2












          2








          2







          Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):



          ValueType expected = ValueType.FLOAT;
          String value = expected.name();

          System.out.println("Name value: " + value);

          ValueType actual = ValueType.valueOf(value);

          if(expected.equals(actual)) System.out.println("Values are equal");





          share|improve this answer













          Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):



          ValueType expected = ValueType.FLOAT;
          String value = expected.name();

          System.out.println("Name value: " + value);

          ValueType actual = ValueType.valueOf(value);

          if(expected.equals(actual)) System.out.println("Values are equal");






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 12 '17 at 17:45









          MikeMike

          2,699285




          2,699285























              0














              public enum Tax {

              NONE(1), SALES(2), IMPORT(3);

              private final int value;
              private Tax(int value) {
              this.value = value;
              }

              public String toString() {
              return Integer.toString(value);
              }
              }

              class Test {
              System.out.println(Tax.NONE); //Just an example.
              }





              share|improve this answer






























                0














                public enum Tax {

                NONE(1), SALES(2), IMPORT(3);

                private final int value;
                private Tax(int value) {
                this.value = value;
                }

                public String toString() {
                return Integer.toString(value);
                }
                }

                class Test {
                System.out.println(Tax.NONE); //Just an example.
                }





                share|improve this answer




























                  0












                  0








                  0







                  public enum Tax {

                  NONE(1), SALES(2), IMPORT(3);

                  private final int value;
                  private Tax(int value) {
                  this.value = value;
                  }

                  public String toString() {
                  return Integer.toString(value);
                  }
                  }

                  class Test {
                  System.out.println(Tax.NONE); //Just an example.
                  }





                  share|improve this answer















                  public enum Tax {

                  NONE(1), SALES(2), IMPORT(3);

                  private final int value;
                  private Tax(int value) {
                  this.value = value;
                  }

                  public String toString() {
                  return Integer.toString(value);
                  }
                  }

                  class Test {
                  System.out.println(Tax.NONE); //Just an example.
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 27 '18 at 12:17









                  deHaar

                  2,50851628




                  2,50851628










                  answered Nov 27 '18 at 11:59









                  Ieshaan SaxenaIeshaan Saxena

                  178




                  178






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8157755%2fhow-to-convert-enum-value-to-int%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                      Calculate evaluation metrics using cross_val_predict sklearn

                      Insert data from modal to MySQL (multiple modal on website)