ProgrammingBackend Developer

How do collections work in Java? What are the differences between ArrayList, LinkedList, and HashMap?

Pass interviews with Hintsage AI assistant

Answer.

In Java, collections implement data structures for working with groups of objects. The main structures are:

  • ArrayList (implements the List interface) stores elements in an array, provides fast access by index, but inserting/removing elements in the middle is slow since it requires shifting elements.

  • LinkedList (also implements List) is built on a doubly linked list. It quickly inserts/removes elements in the middle but has slow access by index since it requires traversing the list from the beginning or the end.

  • HashMap implements the Map interface. It stores key-value pairs. Fast access (O(1)) to values by key is provided through a hash function, but it does not guarantee the order of elements.

List<String> arrayList = new ArrayList<>(); arrayList.add("A"); // fast arrayList.get(0); // fast List<String> linkedList = new LinkedList<>(); linkedList.add("A"); // slightly slower linkedList.add(0, "B"); // fast Map<String, Integer> map = new HashMap<>(); map.put("one", 1); Integer val = map.get("one"); // fast

Trick question.

What is the fundamental difference between HashMap and Hashtable, and why is Hashtable rarely used in modern code?

Answer: HashMap is not synchronized, allows null for both key and value. Hashtable is synchronized (multiple threads can work with one object without compromising integrity), but does not allow null and is slower. In modern code, ConcurrentHashMap is more commonly used for thread safety, as it is more efficient and better configured for multithreaded computations.

Map<String, String> map1 = new HashMap<>(); map1.put(null, "value"); // OK Map<String, String> map2 = new Hashtable<>(); map2.put(null, "value"); // NullPointerException

Examples of real mistakes due to a lack of knowledge about the subtleties of the topic.


Story

In a student accounting system, ArrayList was used for frequent insertions and deletions in the middle of the list, which led to significant performance degradation with a large volume of data. After switching to LinkedList, the situation normalized.


Story

In a multi-threaded CRM system, HashMap was used to store data between threads without synchronization, which occasionally led to inconsistent data and crashes due to race conditions. After switching to ConcurrentHashMap, the bug was resolved.


Story

A developer attempted to add a null key to Hashtable, unaware of the restriction. This caused a NullPointerException, and it took a long time to figure out why the application was crashing unexpectedly.