Summary: Arrays vs. Collections && The differences between Collection Interface and Collections Class
Java offers two types of constructs where you can store multiple values or objects of the same type: arrays and collections (for System Dynamics models AnyLogic also offers HyperArray, also known as "subscripts", – a special type of collection for dynamic variables).
Array or collection? Arrays are simple constructs with linear storage of fixed size and therefore they can only store a given number of elements. Arrays are built into the core of Java language and the array-related Java syntax is very easy and straightforward, for example the nth element of the array can be obtained as array[n]. Collections are more sophisticated and flexible. First of all, they are resizable: you can add any number of elements to a collection. A collection will automatically handle deletion of an element from any position. There are several types of collections with different internal storage structure (linear, list, hash set, tree, etc.) and you can choose a collection type best matching your problem so that your most frequent operations will be convenient and efficient. Collections are Java classes and syntax for obtaining, e.g., the nth element of acollection of type ArrayList is collection.get(n).
From a capability perspective, while both can store references to objects:
- Arrays can store primitives
- Collections can not store primitives (although they can store the primitive wrapper classes, such as
Integer
etc)
One important difference, commonly not understood by programmers new to java, is one of usability and convenience, especially given that Collections automatically expand in size when needed.
Collection
, as its javadoc says is "The root interface in the collection hierarchy." This means that every single class implementing Collection
in any form is part of the Java Collections Framework.
The Collections Framework is Java's native implementation of data structure classes (with implementation specific properties) which represent a group of objects which are somehow related to each other and thus can be called a collection.
Collections
is merely an utility method class for doing certain operations, for example adding thread safety to your ArrayList instance by doing this:
List<MyObj> list = Collections.synchronizedList(new Arraylist<MyObj>());
The main difference in my opinion is that Collection
is base interface which you may use in your code as a type for object (although I wouldn't directly recommend that) while Collections
just provides useful operations for handling the collections.