Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a few ways:</p> <p><strong>Double brace initialization</strong></p> <p>This is a technique which creates an anonymous inner class which has an instance initializer which adds <code>String</code>s to itself when an instance is created:</p> <pre><code>Set&lt;String&gt; s = new HashSet&lt;String&gt;() {{ add("a"); add("b"); }} </code></pre> <p>Keep in mind that this will actually create an new subclass of <a href="http://java.sun.com/javase/6/docs/api/java/util/HashSet.html" rel="noreferrer"><code>HashSet</code></a> each time it is used, even though one does not have to explicitly write a new subclass.</p> <p><strong>A utility method</strong></p> <p>Writing a method that returns a <a href="http://java.sun.com/javase/6/docs/api/java/util/Set.html" rel="noreferrer"><code>Set</code></a> which is initialized with the desired elements isn't too hard to write:</p> <pre><code>public static Set&lt;String&gt; newHashSet(String... strings) { HashSet&lt;String&gt; set = new HashSet&lt;String&gt;(); for (String s : strings) { set.add(s); } return set; } </code></pre> <p>The above code only allows for a use of a <code>String</code>, but it shouldn't be too difficult to allow the use of any type using generics.</p> <p><strong>Use a library</strong></p> <p>Many libraries have a convenience method to initialize collections objects.</p> <p>For example, <a href="http://code.google.com/p/google-collections/" rel="noreferrer">Google Collections</a> has a <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Sets.html#newHashSet(E...)" rel="noreferrer"><code>Sets.newHashSet(T...)</code></a> method which will populate a <code>HashSet</code> with elements of a specific type.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload