Upload
dhrubo-kayal
View
730
Download
0
Embed Size (px)
DESCRIPTION
Citation preview
ContainersDhrubojyoti Kayal
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
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
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
Declare an ArrayList and fill 100 integers in it.
Now loop through the list to print the list.
Exercise
List list = new ArrayList(); list.add(1); list.add("john"); Integer val2 = (Integer) list.get(1);
Paving way for Generics
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
Declare an ArrayList and fill it with 100 integers
Now iterate the list using for each loop
Exercise
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
Repeat the previous example with an Iterator
Excercise
Concrete implementation of Set interface Duplicate free collection Opmtized for rapid lookup Set set = new HashSet set.add(1); set.contains(1) boolean
HashSet
Declare an integer array with 6 elements with elements – {1,5,3,5,6,3}
Now find the duplicates in that array.
Excercise
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
Write a Java program to implement a Queue with a LinkedList
Write a Java program to implement a Stack with a LinkedList
Excercise
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
Q&A