title: How to declare an ArrayList?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/147468/why-should-the-interface-for-a-java-class-be-prefered">Why should the interface for a Java class be prefered?</a>  </p>
  </blockquote>
  
  
  
  <p>I m relatively new to java and i have just started on collections framework.
  While on <code>ArrayList</code> I encountered on two ways people declare it. For example to declare an <code>ArrayList</code> of <code>String</code>s :</p>
  
  <pre><code>List&lt;String&gt; l = new ArrayList&lt;String&gt;();
  </code></pre>
  
  <p>or</p>
  
  <pre><code>ArrayList&lt;String&gt; al = new ArrayList&lt;String&gt;();
  </code></pre>
  
  <p>Which one of these two should I use and what is the difference between them?</p>
  
  <p>I know that the actual methods called are decided at runtime and hence the methods called will all be of <code>ArrayList</code> class only but still the first declaration restricts the methods that can be called.</p>
  
  <p>The first way is, I have heard, called "coding to an interface". Any method will be invoked using the variable <code>l</code> and hence only methods provided by <code>List</code> interface can be called, whereas, in the second example we can call all the methods provided not only by <code>List</code> but by the <code>Object</code> class also (like <code>finalize()</code>, <code>wait()</code> etc). So why even in the first place people even use the first declaration??</p>