java - Issue with static code in Android -


i building own class, similar enum. here's code:

public final class myclass {     public final static myclass v1 = new myclass("v1");     public final static myclass v2 = new myclass("v2");     public final static myclass v3 = new myclass("v3");      private static map<string, myclass> values;     private final string name;      private myclass(string name) {         this.name = name;         if (values == null)             values = new hashmap<>();         values.put(name,this);     }      public static myclass[] values() {         return values.values().toarray(new myclass[values.size()]);     }      public static myclass valueof(string key) {                 return values.get(key);         }      public string getname() {                 return name;         }      public string tostring() {          return getname();      }      public static void print() {         iterator<map.entry<string, myclass>> = values.entryset().iterator();         while (i.hasnext()) {             string key = i.next().getkey();             system.out.println(myclass.class.getsimplename() + ": " + key + ", " + values.get(key));         }     } } 

i observing weird behavior: when try invoke myclass.valueof("v1") null. tried debug and:

  • the constructor invoked long before valueof invoked (when invoke print, gets invoked 3 times)
  • values gets populated (last constructor invocation, of course, takes map size 3, expected.
  • when in valueof, values empty

====update

only if in debug mode , put breakpoint in print method, can see "enum-like-class" values printed in console. when htis, valueof returns correct results.

what's happening?

currently, best way found tackle issue move values definition , initialization before other static variables. way, gets initialized before constructors invoked.

look @ this: static initializer not called on activity creation


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -