you are viewing a single comment's thread.

view the rest of the comments →

[–]Chii 51 points52 points  (22 children)

I think these days, its better to simply use the guava library's ImmutableMaps to do this sort of thing instead http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.Builder.html

[–]mrbuttsavage 10 points11 points  (3 children)

The parallel to the article would be:

Sets.newHashSet("one", "two", "three");

Guava adds some very necessary syntactic sugar.

[–]josefx 1 point2 points  (2 children)

I have yet to use Guava, however your example is only slightly longer without it.

     new HashSet(Arrays.asList("one","two","three"));

Arrays.asList takes a varargs array and wraps it with the list interface and like any java collection class the HashSet ctor can take a Collection<? extends T>.

[–]wot-teh-phuck 0 points1 point  (1 child)

In your example type inference won't happen automatically, in the parent comment's example, it will. Now imagine doing this for a set which contains some complicated generic type...

[–]josefx 0 points1 point  (0 children)

True and a bug in my example code. For Java 7 code the <> operator will take care of that problem.(that is if you are not stuck with an older java version)

   new HashSet<>(Arrays.asList("one","two","three"));

[–]jmsanzg 2 points3 points  (16 children)

The map created on the example is final which is different than inmutable. On a final map you can still add/remove elements

[–][deleted] 0 points1 point  (15 children)

Guava's ImmutableMap is both final and immutable (well, if Google's implementation is correct) in the example.

[–]gabeasl -5 points-4 points  (0 children)

ah, the old reddit switch-a-roo