This document discusses various Java collection classes including List, Map, Set, and Iterator. It provides examples of how to declare and use ArrayList, LinkedList, HashSet, and HashMap. It also covers generics, duplicates, and implementing a queue and stack with LinkedList.
2. Collections a sequence of individual elements with one or more rules applied to them. List, Queue, Set Map a group of key-value object pairs, allowing you to look up a value using a key. Basics
3. Lists promise to maintain elements in a particular sequence. ArrayList - excels at randomly accessing elements, but is slower when inserting and removing elements in the middle of a List. LinkedList - which provides optimal sequential access, with inexpensive insertions and deletions from the middle of the List. List
4. List list = new ArrayList(); list.add(1); Integer val = (Integer) list.get(0); System.out.println(list.size()); list.add(2); list.remove(0); System.out.println(list.size()); List in Action
5. Declare an ArrayList and fill 100 integers in it. Now loop through the list to print the list. Exercise
6. List list = new ArrayList(); list.add(1); list.add("john"); Integer val2 = (Integer) list.get(1); Paving way for Generics
7. Allow only a specific type to be added in a list Runtime system takes care of the type casts under the hood. List<Integer> list = new ArrayList<Integer> list.add(1); list.add(“hi”); Generics
8. Declare an ArrayList and fill it with 100 integers Now iterate the list using for each loop Exercise
9. An iterator is an object whose job is to move through a sequence and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence. Java Iterator can move in only one direction Typical workflow Get iterator object - list.iterator() Get the next object in the sequence with next( ). See if there are any more objects in the sequence with hasNext( ). Iterator
11. Concrete implementation of Set interface Duplicate free collection Opmtized for rapid lookup Set set = new HashSet set.add(1); set.contains(1) boolean HashSet
12. Declare an integer array with 6 elements with elements – {1,5,3,5,6,3} Now find the duplicates in that array. Excercise
13. Implements the basic List interface Insertion and removal in the middle of the List is more efficient than ArrayList It is less efficient for random-access operations. Adds methods that allow it to be used as a stack, a Queue or a double-ended queue (deque). add(Object o) addFirst(Object o) addLast(Object o) removeFirst() removeLast() getFirst(); getLast(); LinkedList
14. Write a Java program to implement a Queue with a LinkedList Write a Java program to implement a Stack with a LinkedList Excercise
15. Implementation of Map Key Value pair Useful for cache and lookup Map<String, Integer> map = new HashMap<String, Integer> map.get(key) map.put(key,value); HashMap