One of the defining characteristics of the Java Collections Framework is that it is an interface-based type system. The API is defined largely through interfaces that may extend other interfaces. The base interface is Collection
.
In this way, most of the collection implementations (eg. ArrayList
, HashSet
, etc.) are also assignable to variables or parameters of type Collection
). This provides a lot of expressive power to the Framework.
Most of the Java Collection Framework implementations have a constructor that accepts a parameter of type Collection
. This is called the "conversion constructor" because it allows you to pass in any collection in the framework whose type extends the Collection
interface (and most do) and get that collection represented as a collection of the newly constructed type.
In other words:
List<String> list1 = Arrays.asList(new String[] { "one", "two", "three" });
HashSet<String> set1 = new HashSet<>(list1);
The variable set1
will end up containing a reference to a HashSet
instance containing all the objects that are also in the List
instance list1
. The conversion constructor, in effect, converted the representation of your data from a List to a HashSet.
Whenever possible, it is typically a best practice to use an object's interface as its type rather than its implementation type. This gives you much greater flexibility. Therefore "List myList = ..." is preferred over "ArrayList myList = ...".