Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually, probably the "best" way to initialize the <code>ArrayList</code> is the method you wrote, as it does not need to create a new <code>List</code> in any way:</p> <pre><code>ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;(); list.add("A"); list.add("B"); list.add("C"); </code></pre> <p>The catch is that there is quite a bit of typing required to refer to that <code>list</code> instance.</p> <p>There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):</p> <pre><code>ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;() {{ add("A"); add("B"); add("C"); }}; </code></pre> <p>However, I'm not too fond of that method because what you end up with is a subclass of <code>ArrayList</code> which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.</p> <p>What would have been nice was if the <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001193.html" rel="noreferrer">Collection Literals proposal</a> for <a href="http://openjdk.java.net/projects/coin" rel="noreferrer">Project Coin</a> was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):</p> <pre><code>List&lt;String&gt; list = ["A", "B", "C"]; </code></pre> <p>Unfortunately it won't help you here, as it will initialize an immutable <code>List</code> rather than an <code>ArrayList</code>, and furthermore, it's not available yet, if it ever will be.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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