Lably
Skip to content

Java collections framework

  • 15 min read
  • 9 chapters

Related on Lably

Through Java (programming language), Class (programming) and Data structure

Although referred to as a framework, it works in a manner of a library. The collections framework provides both interfaces that define various collections and classes that implement them.

Differences from Arrays

Collections and arrays are similar in that they both hold references to objects and they can be managed as a group. However, unlike arrays, Collections do not need to be assigned a certain capacity when instantiated. Collections can grow and shrink in size automatically when objects are added or removed.

Collections cannot hold primitive data types such as int, long, or double. Instead, Collections can hold wrapper classes such as java.lang.Integer, java.lang.Long, or java.lang.Double.

Collections are generic and hence invariant, but arrays are covariant. This can be considered an advantage of generic objects such as Collection when compared to arrays, because under circumstances, using the generic Collection instead of an array prevents run time exceptions by instead throwing a compile-time exception to inform the developer to fix the code. For example, if a developer declares an Object[] object, and assigns the Object[] object to the value returned by a new Long[] instance with a certain capacity, no compile-time exception will be thrown. If the developer attempts to add a String to this Long[] object, the java program will throw an ArrayStoreException. On the other hand, if the developer instead declared a new instance of a Collection<Object> as ArrayList<Long>, the Java compiler will (correctly) throw a compile-time exception to indicate that the code is written with incompatible and incorrect type, thus preventing any potential run-time exceptions.The developer can fix the code by instantianting Collection<Object> as an ArrayList<Object> object. If the code is using Java SE7 or later versions, the developer can instatiate Collection<Object> as an ArrayList<> object by using the diamond operator

Collections are generic and hence reified, but arrays are not reified.

Sign in to keep reading

8 more chapters are free with a Lably account.

More in Computing and communication