0

what is difference between

List<String> l1 = new ArrayList<String>();

and

ArrayList<String> l2 = new ArrayList<String>();

Also which one is better to use?

4castle
  • 32,613
  • 11
  • 69
  • 106
ara
  • 33
  • 6
  • check this out .. http://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java – HuntsMan Jan 07 '17 at 07:49
  • Also please read this: http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface – Tim Biegeleisen Jan 07 '17 at 07:51
  • 2
    The only reason to use `ArrayList` is if you need to call `ensureCapacity()` or `trimToSize()`. – 4castle Jan 07 '17 at 07:52
  • @4castle: Or if the use of an array-list is actually relevant in some way. – ruakh Jan 07 '17 at 07:58
  • 1
    `ArrayList<>` is also a promise of O(1) access times, where `List<>` only promises O(N). – AJNeufeld Jan 07 '17 at 08:18
  • @AJNeufeld please add source of your statement. – dkb Jan 07 '17 at 08:31
  • @dkb Sorry, I was referring specifically to `#get(int)` access times. `ArrayList` implements `RandomAccess`, where as `List` could be a `LinkedList`, which would be O(N). Of course, this refers to what is promised by the interface to external code; the object will always still be a concrete `ArrayList`. – AJNeufeld Jan 07 '17 at 16:59

0 Answers0