Efficiency of Java “Double Brace Initialization”?

In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax: Set<String> flavors = new HashSet<String>() {{ add(“vanilla”); add(“strawberry”); add(“chocolate”); add(“butter pecan”); }}; This idiom creates an anonymous inner class with just an instance initializer in it, which “can use any […] methods in the containing scope”. Main question: … Read more

Efficiency of Java “Double Brace Initialization”?

In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax: Set<String> flavors = new HashSet<String>() {{ add(“vanilla”); add(“strawberry”); add(“chocolate”); add(“butter pecan”); }}; This idiom creates an anonymous inner class with just an instance initializer in it, which “can use any […] methods in the containing scope”. Main question: … Read more

Do the parentheses after the type name make a difference with new?

If ‘Test’ is an ordinary class, is there any difference between: Test* test = new Test; and Test* test = new Test(); 7 s 7 Let’s get pedantic, because there are differences that can actually affect your code’s behavior. Much of the following is taken from comments made to an “Old New Thing” article. Sometimes … Read more

How can I initialise a static Map?

How would you initialise a static Map in Java? Method one: static initialiser Method two: instance initialiser (anonymous subclass) or some other method? What are the pros and cons of each? Here is an example illustrating the two methods: import java.util.HashMap; import java.util.Map; public class Test { private static final Map<Integer, String> myMap = new … Read more

How to directly initialize a HashMap (in a literal way)?

Is there some way of initializing a Java HashMap like this?: Map<String,String> test = new HashMap<String, String>{“test”:”test”,”test”:”test”}; What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastest way to put some “final/static” values in a map that never change and are known in … Read more

Initialization of an ArrayList in one line

I wanted to create a list of options for testing purposes. At first, I did this: ArrayList<String> places = new ArrayList<String>(); places.add(“Buenos Aires”); places.add(“Córdoba”); places.add(“La Plata”); Then, I refactored the code as follows: ArrayList<String> places = new ArrayList<String>( Arrays.asList(“Buenos Aires”, “Córdoba”, “La Plata”)); Is there a better way to do this? 3 33