← Java from Scratch Lesson 65 of 88 · 5 XP

Data structures

Theory

Machine translation, not yet reviewed by a native speaker.

A data structure is a way of storing many values so that the operations you need are fast. An array is good for access by index, but its length is fixed, and inserting into the middle means moving all the elements.

In Java the ready-made structures are the Collections Framework (java.util). The three main interfaces:

interface what it is implementations
List an ordered list, repeats allowed, access by index ArrayList, LinkedList
Set a set: no repeats HashSet, LinkedHashSet, TreeSet
Map a "key → value" dictionary HashMap, LinkedHashMap, TreeMap

Plus queues: Queue, Deque (ArrayDeque, LinkedList), PriorityQueue.

What the operations cost (big O — how the time grows with the number of elements n):

access by index search insert/remove
ArrayList O(1) O(n) O(n) in the middle, O(1) at the end
LinkedList O(n) O(n) O(1) at the ends
HashSet / HashMap — O(1) on average O(1)
TreeSet / TreeMap — O(log n) O(log n), everything is sorted

What's under the hood: - ArrayList — an array that, when it fills up, is replaced with a new one 1.5 times bigger; - HashMap — an array of "buckets": the bucket number is calculated from the key's hashCode(); - TreeMap — a balanced red-black search tree; - LinkedList — a doubly linked list of nodes.

Collections store only objects: instead of int — Integer (Java wraps it by itself, "autoboxing"). The element type is written in angle brackets: List<String>, Map<String, Integer> — these are generics (the last module).

How to choose: by default ArrayList and HashMap; if you need sorting — Tree…; if you need the order of insertion — Linked….

Sign up for free to mark finished lessons and track your progress.