java - Android:I do not understand: static { foo();} -
this question has answer here:
- static initializer in java 8 answers
- static block in java [duplicate] 7 answers
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
Post a Comment