When Are Enum Values Defined?How are enums internally represented in Java?Is Java “pass-by-reference” or...

Is there a verb that means to inject with poison?

Is Screenshot Time-tracking Common?

What's this assembly doing?

What is the industry term for house wiring diagrams?

Has any human ever had the choice to leave Earth permanently?

What is a good reason for every spaceship to carry a weapon on board?

Why is a temp table a more efficient solution to the Halloween Problem than an eager spool?

Equivalent of "illegal" for violating civil law

How would an AI self awareness kill switch work?

What makes papers publishable in top-tier journals?

How does Leonard in "Memento" remember reading and writing?

Taking headphones when quitting job

Should I cite R or RStudio?

Why zero tolerance on nudity in space?

Why didn't the 2019 Oscars have a host?

Methods for writing a code review

Book where a space ship journeys to the center of the galaxy to find all the stars had gone supernova

If angels and devils are the same species, why would their mortal offspring appear physically different?

Eww, those bytes are gross

Why does 0.-5 evaluate to -5?

Can the "Friends" spell be used without making the target hostile?

Does a paladin have to announce that they're using Divine Smite before attacking?

How can I play a serial killer in a party of good PCs?

Integration of two exponential multiplied by each other



When Are Enum Values Defined?


How are enums internally represented in Java?Is Java “pass-by-reference” or “pass-by-value”?Sort a Map<Key, Value> by valuesWhen to use LinkedList over ArrayList in Java?A Java collection of value pairs? (tuples?)How to get an enum value from a string value in Java?Does Java support default parameter values?A 'for' loop to iterate over an enum in JavaHow do I determine whether an array contains a particular value in Java?Comparing Java enum members: == or equals()?Java: instantiating an enum from a number using reflection













9















I'm trying to implement something in a semi-efficient manner. In my program, I have an enumerator representing metrics that are used to pass information around in the program.



I have a class that lets me "compose" these metrics into a single object so I can essentially create a "sentence" to give me complex information without having to do any complex parsing of information. They're essentially bit flags but since I'm using an enum, I can have more than just 64 of them.



The problem is that if I'm instantiating instances of this container class a lot, and I go to create an array like so:



metrics = new boolean[Metrics.values().length];


I feel like creating an array of the enumerated values so often just to request its size is wasteful. I'm wondering if it's possible to just define the size of the enumerated values() in a static context so it's a constant value I don't have to recalculate:



private static final int METRIC_COUNT = Metrics.values().length;


Can I do this? Or would the compiler not have defined the enumerated values before it declares this static variable? I know this isn't the best explanation of my question, but I'm not sure how else to word it.



I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?










share|improve this question


















  • 2





    You can certainly cache the length statically. Though I don't see where the array comes in. If you want to mimic a bit field, consider EnumSet.

    – shmosel
    6 hours ago






  • 2





    stackoverflow.com/a/32354397/2970947

    – Elliott Frisch
    5 hours ago






  • 1





    Further to @ElliotFrisch's link, calling values() does create a copy of the enum's array (as opposed to exposing the Enum's own private one, which would open it to being modified).

    – racraman
    5 hours ago











  • FYI, the enum facility in Java (based on Enum class) is usually just called “enum” or “enum type” to avoid confusion with the interface java.util.Enumeration.

    – Basil Bourque
    5 hours ago


















9















I'm trying to implement something in a semi-efficient manner. In my program, I have an enumerator representing metrics that are used to pass information around in the program.



I have a class that lets me "compose" these metrics into a single object so I can essentially create a "sentence" to give me complex information without having to do any complex parsing of information. They're essentially bit flags but since I'm using an enum, I can have more than just 64 of them.



The problem is that if I'm instantiating instances of this container class a lot, and I go to create an array like so:



metrics = new boolean[Metrics.values().length];


I feel like creating an array of the enumerated values so often just to request its size is wasteful. I'm wondering if it's possible to just define the size of the enumerated values() in a static context so it's a constant value I don't have to recalculate:



private static final int METRIC_COUNT = Metrics.values().length;


Can I do this? Or would the compiler not have defined the enumerated values before it declares this static variable? I know this isn't the best explanation of my question, but I'm not sure how else to word it.



I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?










share|improve this question


















  • 2





    You can certainly cache the length statically. Though I don't see where the array comes in. If you want to mimic a bit field, consider EnumSet.

    – shmosel
    6 hours ago






  • 2





    stackoverflow.com/a/32354397/2970947

    – Elliott Frisch
    5 hours ago






  • 1





    Further to @ElliotFrisch's link, calling values() does create a copy of the enum's array (as opposed to exposing the Enum's own private one, which would open it to being modified).

    – racraman
    5 hours ago











  • FYI, the enum facility in Java (based on Enum class) is usually just called “enum” or “enum type” to avoid confusion with the interface java.util.Enumeration.

    – Basil Bourque
    5 hours ago
















9












9








9


2






I'm trying to implement something in a semi-efficient manner. In my program, I have an enumerator representing metrics that are used to pass information around in the program.



I have a class that lets me "compose" these metrics into a single object so I can essentially create a "sentence" to give me complex information without having to do any complex parsing of information. They're essentially bit flags but since I'm using an enum, I can have more than just 64 of them.



The problem is that if I'm instantiating instances of this container class a lot, and I go to create an array like so:



metrics = new boolean[Metrics.values().length];


I feel like creating an array of the enumerated values so often just to request its size is wasteful. I'm wondering if it's possible to just define the size of the enumerated values() in a static context so it's a constant value I don't have to recalculate:



private static final int METRIC_COUNT = Metrics.values().length;


Can I do this? Or would the compiler not have defined the enumerated values before it declares this static variable? I know this isn't the best explanation of my question, but I'm not sure how else to word it.



I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?










share|improve this question














I'm trying to implement something in a semi-efficient manner. In my program, I have an enumerator representing metrics that are used to pass information around in the program.



I have a class that lets me "compose" these metrics into a single object so I can essentially create a "sentence" to give me complex information without having to do any complex parsing of information. They're essentially bit flags but since I'm using an enum, I can have more than just 64 of them.



The problem is that if I'm instantiating instances of this container class a lot, and I go to create an array like so:



metrics = new boolean[Metrics.values().length];


I feel like creating an array of the enumerated values so often just to request its size is wasteful. I'm wondering if it's possible to just define the size of the enumerated values() in a static context so it's a constant value I don't have to recalculate:



private static final int METRIC_COUNT = Metrics.values().length;


Can I do this? Or would the compiler not have defined the enumerated values before it declares this static variable? I know this isn't the best explanation of my question, but I'm not sure how else to word it.



I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?







java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 6 hours ago









Darin BeaudreauDarin Beaudreau

196116




196116








  • 2





    You can certainly cache the length statically. Though I don't see where the array comes in. If you want to mimic a bit field, consider EnumSet.

    – shmosel
    6 hours ago






  • 2





    stackoverflow.com/a/32354397/2970947

    – Elliott Frisch
    5 hours ago






  • 1





    Further to @ElliotFrisch's link, calling values() does create a copy of the enum's array (as opposed to exposing the Enum's own private one, which would open it to being modified).

    – racraman
    5 hours ago











  • FYI, the enum facility in Java (based on Enum class) is usually just called “enum” or “enum type” to avoid confusion with the interface java.util.Enumeration.

    – Basil Bourque
    5 hours ago
















  • 2





    You can certainly cache the length statically. Though I don't see where the array comes in. If you want to mimic a bit field, consider EnumSet.

    – shmosel
    6 hours ago






  • 2





    stackoverflow.com/a/32354397/2970947

    – Elliott Frisch
    5 hours ago






  • 1





    Further to @ElliotFrisch's link, calling values() does create a copy of the enum's array (as opposed to exposing the Enum's own private one, which would open it to being modified).

    – racraman
    5 hours ago











  • FYI, the enum facility in Java (based on Enum class) is usually just called “enum” or “enum type” to avoid confusion with the interface java.util.Enumeration.

    – Basil Bourque
    5 hours ago










2




2





You can certainly cache the length statically. Though I don't see where the array comes in. If you want to mimic a bit field, consider EnumSet.

– shmosel
6 hours ago





You can certainly cache the length statically. Though I don't see where the array comes in. If you want to mimic a bit field, consider EnumSet.

– shmosel
6 hours ago




2




2





stackoverflow.com/a/32354397/2970947

– Elliott Frisch
5 hours ago





stackoverflow.com/a/32354397/2970947

– Elliott Frisch
5 hours ago




1




1





Further to @ElliotFrisch's link, calling values() does create a copy of the enum's array (as opposed to exposing the Enum's own private one, which would open it to being modified).

– racraman
5 hours ago





Further to @ElliotFrisch's link, calling values() does create a copy of the enum's array (as opposed to exposing the Enum's own private one, which would open it to being modified).

– racraman
5 hours ago













FYI, the enum facility in Java (based on Enum class) is usually just called “enum” or “enum type” to avoid confusion with the interface java.util.Enumeration.

– Basil Bourque
5 hours ago







FYI, the enum facility in Java (based on Enum class) is usually just called “enum” or “enum type” to avoid confusion with the interface java.util.Enumeration.

– Basil Bourque
5 hours ago














3 Answers
3






active

oldest

votes


















6














EnumSet




"compose" these metrics into a single object



essentially bit flags




Sounds like you need a bit-array, with a bit flipped for the presence/absence of each predefined enum value.



If so, no need to roll your own. Use EnumSet or EnumMap. These are special implementations of the Set and Map interfaces. These classes are extremely efficient because of their nature handling enums, taking very little memory and being very fast to execute.



Take for example the built-in DayOfWeek enum. Defines seven objects, one for each day of the week per ISO 8601 calendar.



Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;


Use the convenient methods of Set such as contains.



boolean isTodayWeekend = weekend.contains( LocalDate.now().getDayOfWeek() ) ;


If you loop the elements of the set, they are promised to be provided in the order in which they are defined within the enum (their “natural” order). So, logically, an EnumSet should have been marked as a SortedSet, but mysteriously was not so marked. Nevertheless, you know the order. For example, looping EnumSet.allOf( DayOfWeek.class ) renders DayOfWeek.MONDAY first and DayOfWeek.SUNDAY last (per the ISO 8601 standard).




When Are Enum Values Defined?




The elements of an enum are defined at compile-time, and cannot be modified at runtime (unless you pull tricks with reflection). Each named variable is populated with an instance when the class is loaded. See Section 8.9, Enum Types of Java Language Specification.



If you define an enum Pet with DOG, CAT, and BIRD, then you know you will have exactly three instances at all times during runtime.



You can count the number of elements defined in an enum in at least two ways:




  • Calling the values method generated by the compiler for any enum, where you can ask the size of the resulting array, as you show in your Question.
    int countDows = DayOfWeek.values().length() ;

  • Calling Set::size after creating an EnumSet of all enum instances.
    int countDows = EnumSet.allOf( DayOfWeek.class ).size() ;






share|improve this answer





















  • 1





    @DarinBeaudreau You will find EnumSet (and EnumMap) quite useful. Notice the methods to copy, invert (complementOf), empty (noneOf & removeAll), and quickly define a subset of a large number of elements (range).

    – Basil Bourque
    5 hours ago











  • FWIW: It's possible to define new enum elements by using reflection in hacky ways.

    – immibis
    3 hours ago











  • @immibis I almost added a mention of that originally. Your comment prompted me to do so now.

    – Basil Bourque
    1 hour ago



















5















private static final int METRIC_COUNT = Metrics.values().length;


Can I do this?




Yes, you can. This is exactly the right way to cache the length and ensure it's only computed once.




I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?




Yep. As defined, METRIC_COUNT is also computed at runtime.






share|improve this answer































    -2














    I don't know if you need to do this in this case, but I think I understand the more general problem of not being able to compute a constant early in your execution. I've had this problem. The solution I've used is something like this...compute METRICS_COUNT later on, when you're ready to use it and are sure that the Metrics object is defined, but still only once:



    private static int METRIC_COUNT = -1;

    public static int getMetricsCount() {
    if (METRIC_COUNT < 0)
    METRIC_COUNT = Metrics.values().length;
    return METRIC_COUNT;
    }


    Note that I'm not addressing the Enum problem specifically, as others are in the comments. I'm just proposing a way of putting off setting of a global value until just when it is needed.






    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%2f54877109%2fwhen-are-enum-values-defined%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      6














      EnumSet




      "compose" these metrics into a single object



      essentially bit flags




      Sounds like you need a bit-array, with a bit flipped for the presence/absence of each predefined enum value.



      If so, no need to roll your own. Use EnumSet or EnumMap. These are special implementations of the Set and Map interfaces. These classes are extremely efficient because of their nature handling enums, taking very little memory and being very fast to execute.



      Take for example the built-in DayOfWeek enum. Defines seven objects, one for each day of the week per ISO 8601 calendar.



      Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;


      Use the convenient methods of Set such as contains.



      boolean isTodayWeekend = weekend.contains( LocalDate.now().getDayOfWeek() ) ;


      If you loop the elements of the set, they are promised to be provided in the order in which they are defined within the enum (their “natural” order). So, logically, an EnumSet should have been marked as a SortedSet, but mysteriously was not so marked. Nevertheless, you know the order. For example, looping EnumSet.allOf( DayOfWeek.class ) renders DayOfWeek.MONDAY first and DayOfWeek.SUNDAY last (per the ISO 8601 standard).




      When Are Enum Values Defined?




      The elements of an enum are defined at compile-time, and cannot be modified at runtime (unless you pull tricks with reflection). Each named variable is populated with an instance when the class is loaded. See Section 8.9, Enum Types of Java Language Specification.



      If you define an enum Pet with DOG, CAT, and BIRD, then you know you will have exactly three instances at all times during runtime.



      You can count the number of elements defined in an enum in at least two ways:




      • Calling the values method generated by the compiler for any enum, where you can ask the size of the resulting array, as you show in your Question.
        int countDows = DayOfWeek.values().length() ;

      • Calling Set::size after creating an EnumSet of all enum instances.
        int countDows = EnumSet.allOf( DayOfWeek.class ).size() ;






      share|improve this answer





















      • 1





        @DarinBeaudreau You will find EnumSet (and EnumMap) quite useful. Notice the methods to copy, invert (complementOf), empty (noneOf & removeAll), and quickly define a subset of a large number of elements (range).

        – Basil Bourque
        5 hours ago











      • FWIW: It's possible to define new enum elements by using reflection in hacky ways.

        – immibis
        3 hours ago











      • @immibis I almost added a mention of that originally. Your comment prompted me to do so now.

        – Basil Bourque
        1 hour ago
















      6














      EnumSet




      "compose" these metrics into a single object



      essentially bit flags




      Sounds like you need a bit-array, with a bit flipped for the presence/absence of each predefined enum value.



      If so, no need to roll your own. Use EnumSet or EnumMap. These are special implementations of the Set and Map interfaces. These classes are extremely efficient because of their nature handling enums, taking very little memory and being very fast to execute.



      Take for example the built-in DayOfWeek enum. Defines seven objects, one for each day of the week per ISO 8601 calendar.



      Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;


      Use the convenient methods of Set such as contains.



      boolean isTodayWeekend = weekend.contains( LocalDate.now().getDayOfWeek() ) ;


      If you loop the elements of the set, they are promised to be provided in the order in which they are defined within the enum (their “natural” order). So, logically, an EnumSet should have been marked as a SortedSet, but mysteriously was not so marked. Nevertheless, you know the order. For example, looping EnumSet.allOf( DayOfWeek.class ) renders DayOfWeek.MONDAY first and DayOfWeek.SUNDAY last (per the ISO 8601 standard).




      When Are Enum Values Defined?




      The elements of an enum are defined at compile-time, and cannot be modified at runtime (unless you pull tricks with reflection). Each named variable is populated with an instance when the class is loaded. See Section 8.9, Enum Types of Java Language Specification.



      If you define an enum Pet with DOG, CAT, and BIRD, then you know you will have exactly three instances at all times during runtime.



      You can count the number of elements defined in an enum in at least two ways:




      • Calling the values method generated by the compiler for any enum, where you can ask the size of the resulting array, as you show in your Question.
        int countDows = DayOfWeek.values().length() ;

      • Calling Set::size after creating an EnumSet of all enum instances.
        int countDows = EnumSet.allOf( DayOfWeek.class ).size() ;






      share|improve this answer





















      • 1





        @DarinBeaudreau You will find EnumSet (and EnumMap) quite useful. Notice the methods to copy, invert (complementOf), empty (noneOf & removeAll), and quickly define a subset of a large number of elements (range).

        – Basil Bourque
        5 hours ago











      • FWIW: It's possible to define new enum elements by using reflection in hacky ways.

        – immibis
        3 hours ago











      • @immibis I almost added a mention of that originally. Your comment prompted me to do so now.

        – Basil Bourque
        1 hour ago














      6












      6








      6







      EnumSet




      "compose" these metrics into a single object



      essentially bit flags




      Sounds like you need a bit-array, with a bit flipped for the presence/absence of each predefined enum value.



      If so, no need to roll your own. Use EnumSet or EnumMap. These are special implementations of the Set and Map interfaces. These classes are extremely efficient because of their nature handling enums, taking very little memory and being very fast to execute.



      Take for example the built-in DayOfWeek enum. Defines seven objects, one for each day of the week per ISO 8601 calendar.



      Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;


      Use the convenient methods of Set such as contains.



      boolean isTodayWeekend = weekend.contains( LocalDate.now().getDayOfWeek() ) ;


      If you loop the elements of the set, they are promised to be provided in the order in which they are defined within the enum (their “natural” order). So, logically, an EnumSet should have been marked as a SortedSet, but mysteriously was not so marked. Nevertheless, you know the order. For example, looping EnumSet.allOf( DayOfWeek.class ) renders DayOfWeek.MONDAY first and DayOfWeek.SUNDAY last (per the ISO 8601 standard).




      When Are Enum Values Defined?




      The elements of an enum are defined at compile-time, and cannot be modified at runtime (unless you pull tricks with reflection). Each named variable is populated with an instance when the class is loaded. See Section 8.9, Enum Types of Java Language Specification.



      If you define an enum Pet with DOG, CAT, and BIRD, then you know you will have exactly three instances at all times during runtime.



      You can count the number of elements defined in an enum in at least two ways:




      • Calling the values method generated by the compiler for any enum, where you can ask the size of the resulting array, as you show in your Question.
        int countDows = DayOfWeek.values().length() ;

      • Calling Set::size after creating an EnumSet of all enum instances.
        int countDows = EnumSet.allOf( DayOfWeek.class ).size() ;






      share|improve this answer















      EnumSet




      "compose" these metrics into a single object



      essentially bit flags




      Sounds like you need a bit-array, with a bit flipped for the presence/absence of each predefined enum value.



      If so, no need to roll your own. Use EnumSet or EnumMap. These are special implementations of the Set and Map interfaces. These classes are extremely efficient because of their nature handling enums, taking very little memory and being very fast to execute.



      Take for example the built-in DayOfWeek enum. Defines seven objects, one for each day of the week per ISO 8601 calendar.



      Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;


      Use the convenient methods of Set such as contains.



      boolean isTodayWeekend = weekend.contains( LocalDate.now().getDayOfWeek() ) ;


      If you loop the elements of the set, they are promised to be provided in the order in which they are defined within the enum (their “natural” order). So, logically, an EnumSet should have been marked as a SortedSet, but mysteriously was not so marked. Nevertheless, you know the order. For example, looping EnumSet.allOf( DayOfWeek.class ) renders DayOfWeek.MONDAY first and DayOfWeek.SUNDAY last (per the ISO 8601 standard).




      When Are Enum Values Defined?




      The elements of an enum are defined at compile-time, and cannot be modified at runtime (unless you pull tricks with reflection). Each named variable is populated with an instance when the class is loaded. See Section 8.9, Enum Types of Java Language Specification.



      If you define an enum Pet with DOG, CAT, and BIRD, then you know you will have exactly three instances at all times during runtime.



      You can count the number of elements defined in an enum in at least two ways:




      • Calling the values method generated by the compiler for any enum, where you can ask the size of the resulting array, as you show in your Question.
        int countDows = DayOfWeek.values().length() ;

      • Calling Set::size after creating an EnumSet of all enum instances.
        int countDows = EnumSet.allOf( DayOfWeek.class ).size() ;







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 1 hour ago

























      answered 5 hours ago









      Basil BourqueBasil Bourque

      112k28386545




      112k28386545








      • 1





        @DarinBeaudreau You will find EnumSet (and EnumMap) quite useful. Notice the methods to copy, invert (complementOf), empty (noneOf & removeAll), and quickly define a subset of a large number of elements (range).

        – Basil Bourque
        5 hours ago











      • FWIW: It's possible to define new enum elements by using reflection in hacky ways.

        – immibis
        3 hours ago











      • @immibis I almost added a mention of that originally. Your comment prompted me to do so now.

        – Basil Bourque
        1 hour ago














      • 1





        @DarinBeaudreau You will find EnumSet (and EnumMap) quite useful. Notice the methods to copy, invert (complementOf), empty (noneOf & removeAll), and quickly define a subset of a large number of elements (range).

        – Basil Bourque
        5 hours ago











      • FWIW: It's possible to define new enum elements by using reflection in hacky ways.

        – immibis
        3 hours ago











      • @immibis I almost added a mention of that originally. Your comment prompted me to do so now.

        – Basil Bourque
        1 hour ago








      1




      1





      @DarinBeaudreau You will find EnumSet (and EnumMap) quite useful. Notice the methods to copy, invert (complementOf), empty (noneOf & removeAll), and quickly define a subset of a large number of elements (range).

      – Basil Bourque
      5 hours ago





      @DarinBeaudreau You will find EnumSet (and EnumMap) quite useful. Notice the methods to copy, invert (complementOf), empty (noneOf & removeAll), and quickly define a subset of a large number of elements (range).

      – Basil Bourque
      5 hours ago













      FWIW: It's possible to define new enum elements by using reflection in hacky ways.

      – immibis
      3 hours ago





      FWIW: It's possible to define new enum elements by using reflection in hacky ways.

      – immibis
      3 hours ago













      @immibis I almost added a mention of that originally. Your comment prompted me to do so now.

      – Basil Bourque
      1 hour ago





      @immibis I almost added a mention of that originally. Your comment prompted me to do so now.

      – Basil Bourque
      1 hour ago













      5















      private static final int METRIC_COUNT = Metrics.values().length;


      Can I do this?




      Yes, you can. This is exactly the right way to cache the length and ensure it's only computed once.




      I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?




      Yep. As defined, METRIC_COUNT is also computed at runtime.






      share|improve this answer




























        5















        private static final int METRIC_COUNT = Metrics.values().length;


        Can I do this?




        Yes, you can. This is exactly the right way to cache the length and ensure it's only computed once.




        I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?




        Yep. As defined, METRIC_COUNT is also computed at runtime.






        share|improve this answer


























          5












          5








          5








          private static final int METRIC_COUNT = Metrics.values().length;


          Can I do this?




          Yes, you can. This is exactly the right way to cache the length and ensure it's only computed once.




          I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?




          Yep. As defined, METRIC_COUNT is also computed at runtime.






          share|improve this answer














          private static final int METRIC_COUNT = Metrics.values().length;


          Can I do this?




          Yes, you can. This is exactly the right way to cache the length and ensure it's only computed once.




          I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?




          Yep. As defined, METRIC_COUNT is also computed at runtime.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 5 hours ago









          John KugelmanJohn Kugelman

          244k54406457




          244k54406457























              -2














              I don't know if you need to do this in this case, but I think I understand the more general problem of not being able to compute a constant early in your execution. I've had this problem. The solution I've used is something like this...compute METRICS_COUNT later on, when you're ready to use it and are sure that the Metrics object is defined, but still only once:



              private static int METRIC_COUNT = -1;

              public static int getMetricsCount() {
              if (METRIC_COUNT < 0)
              METRIC_COUNT = Metrics.values().length;
              return METRIC_COUNT;
              }


              Note that I'm not addressing the Enum problem specifically, as others are in the comments. I'm just proposing a way of putting off setting of a global value until just when it is needed.






              share|improve this answer






























                -2














                I don't know if you need to do this in this case, but I think I understand the more general problem of not being able to compute a constant early in your execution. I've had this problem. The solution I've used is something like this...compute METRICS_COUNT later on, when you're ready to use it and are sure that the Metrics object is defined, but still only once:



                private static int METRIC_COUNT = -1;

                public static int getMetricsCount() {
                if (METRIC_COUNT < 0)
                METRIC_COUNT = Metrics.values().length;
                return METRIC_COUNT;
                }


                Note that I'm not addressing the Enum problem specifically, as others are in the comments. I'm just proposing a way of putting off setting of a global value until just when it is needed.






                share|improve this answer




























                  -2












                  -2








                  -2







                  I don't know if you need to do this in this case, but I think I understand the more general problem of not being able to compute a constant early in your execution. I've had this problem. The solution I've used is something like this...compute METRICS_COUNT later on, when you're ready to use it and are sure that the Metrics object is defined, but still only once:



                  private static int METRIC_COUNT = -1;

                  public static int getMetricsCount() {
                  if (METRIC_COUNT < 0)
                  METRIC_COUNT = Metrics.values().length;
                  return METRIC_COUNT;
                  }


                  Note that I'm not addressing the Enum problem specifically, as others are in the comments. I'm just proposing a way of putting off setting of a global value until just when it is needed.






                  share|improve this answer















                  I don't know if you need to do this in this case, but I think I understand the more general problem of not being able to compute a constant early in your execution. I've had this problem. The solution I've used is something like this...compute METRICS_COUNT later on, when you're ready to use it and are sure that the Metrics object is defined, but still only once:



                  private static int METRIC_COUNT = -1;

                  public static int getMetricsCount() {
                  if (METRIC_COUNT < 0)
                  METRIC_COUNT = Metrics.values().length;
                  return METRIC_COUNT;
                  }


                  Note that I'm not addressing the Enum problem specifically, as others are in the comments. I'm just proposing a way of putting off setting of a global value until just when it is needed.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 5 hours ago

























                  answered 5 hours ago









                  SteveSteve

                  794111




                  794111






























                      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%2f54877109%2fwhen-are-enum-values-defined%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

                      VNC viewer RFB protocol error: bad desktop size 0x0I Cannot Type the Key 'd' (lowercase) in VNC Viewer...

                      Tribunal Administrativo e Fiscal de Mirandela Referências Menu de...

                      looking for continuous Screen Capture for retroactivly reproducing errors, timeback machineRolling desktop...