Arrays have a fixed size. Real programs need groups of objects that grow, shrink, avoid duplicates or look things up by key. The Java Collections Framework (java.util) provides ready-made data structures for all of these.
Collection
├── List (ordered, duplicates allowed) ArrayList, LinkedList
├── Set (no duplicates) HashSet, LinkedHashSet, TreeSet
└── Queue (processing order) ArrayDeque, PriorityQueue, LinkedList
Map (key → value, unique keys) HashMap, LinkedHashMap, TreeMap
Generics in one minute#
Collections use generics - the type in angle brackets says what they hold:
List<String> names = new ArrayList<>(); // only Strings allowed
names.add("Asha");
// names.add(42); // compile error - type safety!
String first = names.get(0); // no cast needed
Generics work with objects only, so use wrapper types: List<Integer>, Map<String, Double>. Java converts between int and Integer automatically (autoboxing).
ArrayList - a resizable list#
[Java, C++, Python, SQL] size 4 get(2): Python [Java, C++, MySQL] contains Java? true, index of MySQL: 2 sorted: [C++, Java, MySQL] C++ JAVA MYSQL
ArrayList एक ऐसा array है जो अपने आप बढ़ता-घटता है। add से जोड़ें, get(i) से पढ़ें, set से बदलें, remove से हटाएँ और size() से गिनती लें। <String> (generics) बताता है कि इसमें सिर्फ़ String ही रखी जा सकती हैं - गलत type डालने पर compiler ही रोक देता है।
For a List<Integer>, list.remove(1) removes the element at index 1, not the value 1. To remove the value, write list.remove(Integer.valueOf(1)).
LinkedList and ArrayDeque#
LinkedList is fast at inserting/removing at the ends; ArrayDeque is the recommended stack/queue:
Back button: page3, now on page2 Serving Asha, next Ravi PriorityQueue order: 10 30 40 70
Sets - unique elements#
unique count: 4 LinkedHashSet: [Indore, Bhopal, Ujjain, Dewas] TreeSet: [Bhopal, Dewas, Indore, Ujjain] add Indore again? false union [1, 2, 3, 4, 5], intersection [3, 4]
Maps - key → value#
pen: 100 stapler: null stapler (default): 0 has notebook? true eraser -> 100 notebook -> 45 pen -> 100 keys [eraser, notebook, pen], values [100, 45, 100]
Counting with a map - a pattern you will use forever#
{be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=2}
{m=1, i=4, s=4, p=2}Sorting objects with Comparator#
Aditi 9.47 Nisha 9.47 Kabir 9.16 Yash 7.78 By city: [Yash, Aditi, Nisha, Kabir]
Iterating safely and removing while iterating#
Passed: [72, 91, 66] Without toppers: [72, 66]
Removing from a list inside a for-each loop throws ConcurrentModificationException. Use an Iterator or removeIf.
Writing your own generic class and method#
(Java, 1995) -> 4 17 zebra fruit
Which collection should I use?#
| Need | Use |
|---|---|
| ordered list with index access | ArrayList |
| unique values, fast lookup | HashSet |
| unique values in sorted order | TreeSet |
| key → value, fast | HashMap |
| key → value, sorted by key | TreeMap |
| key → value, insertion order | LinkedHashMap |
| stack or queue | ArrayDeque |
| always take the smallest/highest priority | PriorityQueue |
Summary#
- Use interfaces as variable types (
List,Set,Map) and pick the implementation for the behaviour you need. - Generics (
List<String>) give compile-time type safety; use wrapper types for primitives. getOrDefaultandmergemake counting easy;Comparator.comparing(...).thenComparing(...)sorts objects.- Remove while iterating with an
IteratororremoveIf.