java - Android:I do not understand: static { foo();} -


this question has answer here:

sometimes see it, in class in android:

static {     foo(); } 
  • what do?

  • why?

that's static block. executed first time class referenced on code, , calling static method called foo(). can find more static block here. mentioned @commonsware, can initialize static field in 2 different ways, inline declaration time

static arraylist<string> test = new arraylist<string>() {{     add("a");     add("b");     add("c"); }}; 

but can see not easy read. if use static block instead

  static arraylist<string> test;   static {         test = new arraylist<>();         test.add("a");         test.add("b");         test.add("c");     }  

or in question have

static arraylist<string> test; static {   foo(); }  private static void foo() {     test = new arraylist<>();     test.add("a");     test.add("b");     test.add("c"); } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -