-2
Collection<string> collection = new ArrayList<string>();

I noticed the above code is in fact the same as ArrayList<string> collection = new ArrayList<string>();

Would it mean I can have any name to replace the first Collection/ArrayList like

anyname<string> collection = new ArrayList<string>();

Thanks!

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
user3462775
  • 17
  • 1
  • 1
  • 2

5 Answers5

1

You are able to do that because ArrayList implements Collection

Class ArrayList<E>

java.lang.Object
  java.util.AbstractCollection<E>
    java.util.AbstractList<E>
      java.util.ArrayList<E>

All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

----> http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

ArrayList implements the interface Collection so collection can be cast to a Collection

see http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

and this tutorial on using Interfaces http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Collection is a interface, while ArrayList is one of the implementations of Collection.

Because ArrayList --> List --> Collection, so you can declare an ArrayList instance as Collection, List and ArrayList. Other types won't work.

Weibo Li
  • 3,565
  • 3
  • 24
  • 36
0

why-define-a-java-object-using-interface-e-g-map-rather-than-implementation I hope this will help you understand , why use an interface type rather than concrete implementation while initializing an object and storing it's reference to a type variable.

Community
  • 1
  • 1
rogue lad
  • 2,413
  • 2
  • 29
  • 32
-1

With an ArrayList (that implements Collection) you are allowed to do this .

Jeroen
  • 60,696
  • 40
  • 206
  • 339