Error-prone: Detect collections using double brace initialization

Created on 28 Jan 2018  Â·  3Comments  Â·  Source: google/error-prone

Some call sites construct collections via double brace initialization:

new HashSet<String>() {{ add("NU"); add("TK"); add("NC"); add("AC"); }};

error-prone should recommend the more succinct and efficient:

new HashSet<String>(Arrays.asList("NU", "TK", "NC", "AC"));

The former creates an anonymous inner class and an implicit this reference which can prolong the outer class lifetime:

https://blog.nishtahir.com/2015/09/27/why-you-shouldnt-use-the-double-brace-initializer/

Type-NewCheck

Most helpful comment

Or even Guava's Immutable* collections?

All 3 comments

Or suggest Set.of, List.of, or Map.of in about 45 days when Java 10 is out.

On Sat, Jan 27, 2018, 9:46 PM Andrew Gaul notifications@github.com wrote:

Some call sites construct collections via double brace initialization:

new HashSet() {{ add("NU"); add("TK"); add("NC"); add("AC"); }};

error-prone should recommend the more succinct and efficient:

new HashSet(Arrays.asList("NU", "TK", "NC", "AC"));

The former creates an anonymous inner class and an implicit this reference
which can prolong the outer class lifetime:

https://blog.nishtahir.com/2015/09/27/why-you-shouldnt-use-the-double-brace-initializer/

—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/google/error-prone/issues/914, or mute the thread
https://github.com/notifications/unsubscribe-auth/AAEEEYTmsaMpKsq7VLoxgksGUgWLSNQHks5tO9-WgaJpZM4RvinU
.

Oops that's in Java 9!

On Sat, Jan 27, 2018, 9:50 PM Jake Wharton jakewharton@gmail.com wrote:

Or suggest Set.of, List.of, or Map.of in about 45 days when Java 10 is out.

On Sat, Jan 27, 2018, 9:46 PM Andrew Gaul notifications@github.com
wrote:

Some call sites construct collections via double brace initialization:

new HashSet() {{ add("NU"); add("TK"); add("NC"); add("AC"); }};

error-prone should recommend the more succinct and efficient:

new HashSet(Arrays.asList("NU", "TK", "NC", "AC"));

The former creates an anonymous inner class and an implicit this
reference which can prolong the outer class lifetime:

https://blog.nishtahir.com/2015/09/27/why-you-shouldnt-use-the-double-brace-initializer/

—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/google/error-prone/issues/914, or mute the thread
https://github.com/notifications/unsubscribe-auth/AAEEEYTmsaMpKsq7VLoxgksGUgWLSNQHks5tO9-WgaJpZM4RvinU
.

Or even Guava's Immutable* collections?

Was this page helpful?
0 / 5 - 0 ratings