Sitemap

Java Collection Framework

5 min readFeb 13, 2021

--

Press enter or click to view image in full size
Photo by Sharon McCutcheon on Unsplash

Java Collection Framework

  • Reduced programming effort due to ready to use code
  • Increased performance because of high-performance implementations of data structures and algorithms
  • Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth
  • Easy to learn APIs by learning only some top level interfaces and supported operations

Collection Interface Does Not Extend Cloneable And Serializable Interface, and if you need them use alternatives.

Map Interface Does Not Extend Collection Interface, because it needs key-value pairs.

A java list is a “ordered” collection of elements. can have duplicates. implemented by Stack, Vector, ArrayList and LinkedList

Set Interface models the mathematical set in set theory. no duplicates allowed. not an ordered list.

ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements.

Can’t add to a Iterator as sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() methods.

Exceptions

Unsupportedoperationexception — for example adding to a readonly list.

Concurrentmodificationexception — find another alternative iterator which are fail-safe or you can use ConcurrentHashMap and CopyOnWriteArrayList classes.

Arraylist And Vector

ArrayList is not synchronized, increases it size by 50% dynamically. Empty Inialized with default capacity of 10.

Vector is synchronized. Increases it size by 100% dynamically

Arraylist And Linkedlist

ArrayList uses a dynamic array. not efficient for manipulation because a lot of shifting is required. better to store and fetch data.

LinkedList uses doubly linked list where each record has three fields for next previous and data. efficient for data manipulation.

  • LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
  • LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node

Iterator And Listiterator

Iterator traverses the elements in forward direction only whereas ListIterator traverses in forward and backward.

Iterator can be used in List, Set and Queue. ListIterator can be used in List only.

Iterator And Enumeration

Enumeration can traverse only legacy elements, faster than Iterator, is not fail-fast.

Iterator can traverse legacy and non-legacy elements. slower than Enumeration, will fail-fast.

ListIterator and Enumeration allows add() remove() methods. Iterator can not add, only remove.

List And Set

List can contain duplicate elements whereas Set contains only unique elements. Both allow null values.

List And Map

List is collection of elements where as map is collection of key-value pairs. They have separate top level interface, separate set of generic methods, different supported methods and different views of collection.

Hashset And Treeset

HashSet maintains no order whereas TreeSet maintains ascending order.

Treeset And Sortedset

SortedSet is an interface which TreeSet implements.

Set And Map

Set contains values only whereas Map contains key and values both.

Hashset And Hashmap

Get Nuwan Zen’s stories in your inbox

Join Medium for free to get updates from this writer.

HashMap is collection of key-value pairs whereas HashSet is un-ordered collection of unique elements. HashSet can be iterated but HashMap need to convert into Set to be iterated.

Hashset has hashmap internally and present it as hashset by showing only value field.

Hashmap And Treemap

HashMap maintains no order but TreeMap maintains ascending order.

HashMap is key-value pairs. TreeMap is special form of HashMap which maintains the order.

Map

all keys inserted into the map must implement the Comparable interface to decide the ordering.

Hashmap And Hashtable

HashMap is not synchronized, so its not thread safe and fast, can contain one null key and multiple null values.

Hashtable is synchronized, so its thread safe and hence slow, cannot contain any null key or null value.

Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not.

Collection And Collections

Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

Comparable And Comparator

Comparable provides only one sort of sequence, It provides one method named compareTo(), java.lang package.

Comparator provides multiple sort of sequences, It provides one method named compare(). java.util package.

To sort the data elements a class needs to implement Comparator or Comparable interface. all collection which have feature of automatic sorting, uses compare methods to ensure the correct sorting of elements. Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern.

Synchronizing(Make A Collection Thread Safe)

Collections class provides methods to make synchronized — synchronizedList(), synchronizedSet(), synchronizedSortedSet(), synchronizedMap(), synchronizedSortedMap()

Generic Collection

It is typesafe and checked at compile time. don’t need typecasting

Handling Hash-collision

Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision

Dictionary Class

provides the capability to store key-value pairs

Default Size Of Load Factor In Hashing Based Collection

The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

Code

Arrays.asList() can convert an array to arrayList.

Collections.reverse(list) to reverse a list

Collections And Arrays Classes

Are utility classes to support collection framework core classes to get read-only/ synchronized collections, sort etc. Arrays class can convert array to a collection objects, coping or working with array objects.

Queue And Stack

Use a queue if you want to process a stream of incoming items in the order that they are received.Good for work lists and handling requests. first-in-first-out is the sorting order.

Use a stack if you want to push and pop from the top of the stack only. Good for recursive algorithms. last-in-first-out sorting order.

Blockingqueue

For example, if we want to delete an element from an empty queue, then the blocking queue allows the delete operation to wait until the queue contains some elements to be deleted. BlockingQueue methods can throws an exception, returns a special value, blocks the current thread indefinitely, blocks the current thread with a timeout.

Fail-fast And Fail-safe

Fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection. Fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

Fail-safe iterators are just opposite to fail-fast. They never fail if you modify the underlying collection on which they are iterating, because they work on clone of Collection instead of original collection. Iterator of CopyOnWriteArrayList and ConcurrentHashMap is an example of fail-safe Iterator.

Ref: https://www.wisdomjobs.com/e-university/java-collections-framework-interview-questions.html

Read my other blogs:

--

--

Nuwan Zen
Nuwan Zen

Written by Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!