1

I found in this site http://howtodoinjava.com/2012/11/20/double-brace-initialization-in-java/ a new way to start my collection

I always have a doubt about java

Can I have one structure like with do in Delphi, to make my code be like this

        Set<String> params = new HashSet<String>() {
        {
            add("param one");
            add("param two");
            add("param three");
            add("param four");
        }
    };

And where can I find other interesting practices like that showed in site?

Thanks

Jim Ferrans
  • 30,582
  • 12
  • 56
  • 83
Diego Macario
  • 1,240
  • 2
  • 21
  • 33
  • Have you tested the code? I don't think it will work. – Tareq Mar 26 '13 at 17:01
  • @Tareq: It does work. It just looks odd because most people forgot about initializer blocks. – Aaron Digulla Mar 26 '13 at 17:01
  • Not a good idea though – Tareq Mar 26 '13 at 17:07
  • As nice as it is to keep the code short, one should be aware that this use of double-brace initialization creates an anonymous class. This means that it actually changes the runtime type of the collection. This can lead to unexpected behavior with serialization (when the class is not available when deserializing for example). – Durandal Mar 26 '13 at 17:19

1 Answers1

0

People come up with great new ways to solve problems in Java all the time. But there are only few places where you can actually find compilations of such tricks.

A good place to start is to use frameworks like Spring and Guava because they contains state-of-the-art tricks that will make your life much easier (and your code smaller and safer after a while).

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820