Download presentation
Presentation is loading. Please wait.
Published byAlvin Davidson Modified over 9 years ago
1
Collections Mrs. C. Furman April 21, 2009
2
Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet HashMap implements Map TreeMap implements SortedMap
3
Iterators Iterators interface methods: next – gets the next element of the collection hasNext – returns if there is a next element remove – removes the current element from the collection.
4
Iterators Cont. Each collection class defines it own implementation of the Iterator methods in a class that’s invisible to the user of the collection An Iterator object is created using the iterator method. –Iterator itr = c.iterator(); This point itr at the start of the collection. All elements are returned in proper order.
5
Iterators Cont. Traversal through a list with an iterator: for (itr = c.iterator(); itr.hasNext();) { /*code with a class to itr.next() which advances itr, so we do not need a step expression in our for loop*/ } List, ArrayList and LinkedList have a expanded Iterator… ListIterator, which allows us to move in both directions, as well as add() and set()
6
List Interface A class that implements List is a sequence of elements. Duplicates are allowed. Indexes start at 0 (first index) … length -1 A list allows you to: –Access an element at any position in the list using its integer index. –Insert an element anywhere in the list –Iterate over all elements using ListIterator or Iterator.
7
List Interface Methods of List: boolean add(Object obj) – adds element at end int size() – returns number of elements Object get (int index) – returns the Object at the index Object set(int index, Object obj) – sets the element at the index to obj. Iterator iterator() – creates an iterator starting at the first element. ListIterator listIterator() – creates a listIterator starting at the first element.
8
Some reminders… ArrayList is an array implementation of List interface. ArrayLists can change size at run-time, while an array has a fixed size. Shifting elements caused by insertion and deletion is handled automatically with ArrayLists. ArrayList insertion is O(1). If we need to worry about resizing… inserting n elements.. O(n). In general it is more efficient to iterate through list, rather than using indexes. list1.equals(list2) returns true iff the lists contain the same elements in the same order.
9
ArrayList Methods for ArrayList: ArrayList() – constructs an empty list.. only stores Objects void add(int index, Object obj) – adds the object at the index, inserting and shifting the elements down. Object remove (int index) – removes and returns the obj at the given index. Shifts all elements down to fill in the void.
10
Side Notes on ArrayList add, get, remove and set all take indexes, that can be out of bounds, and therefore throw exceptions. get, remove, and set are out of bounds if.. index = size() add can use the index that is equal to size… so index size() is out of bounds.
11
LinkedList Class implemented using List class. doubly linked list stores 2 links, one to the next and one to the previous element. For AP… the LinkedList class will be restricted to singly –linked lists.
12
LinkedList methods LinkedList() – constructor void addFirst(Object obj) – inserts obj at the front of the list. void addLast (Object obj) – appends obj to the end of the list. Object getFirst() – returns first element Object getLast() – returns the last element Object removeFirst() – Removes and returns the first element in the list Object removeLast() – Removes and returns the last element in the list.
13
ArrayList vs. LinkedList Insert at frontadd(0, obj) O(n) shifts all the element addFirst (obj) O(1). Insert at Endadd(obj) O(1) O(n) – adding n elements add(obj) O(1) Delete at frontremove(0) O(n) – shifting n elements down removeFirst() O(1) Delete at Endremove (size() -1 ) O(1) removeLast() O(1) Insert in middleadd(Index, obj) O(1) – find the spot O(n) – insert the element. itr.add() O(n) – find the spot O(1) – insert.
14
Delete in middleremove (index) O(1) – access O(n) – shift the elements into the void itr.remove() O(n) – access to insertion point O(1) – delete Change value in middle set (index, obj) O(1). Fast access set (index, obj) O(n) traversal to location element For most applications ArrayList is faster! ArrayList has fast access to any element, while LinkedList has to traverse the list to get to anything but 1 st and last. LinkedList needs to allocate a node for each element in the list whereas ArrayList does not. Use LinkedLists for: Programs that require frequent additions to front of list. If you need to iterate through the entire list deleting elements as you go
15
The Set Interface A set is a collection: –Contains NO duplicate elements –May contain a null element –Based on a mathematical set. Allows us to: –Insert a nonduplicate element –Remove an element –Test if a given element is in set –Iterate over the elements using Iterator
16
Sets Continue Sets have 2 Implementations: –HashSet, which stores its elements in a hash table(stay tuned!!) –TreeSet, which stores its elements in a balanced binary search tree 2 sets are equal iff the contain the same elements!!
17
Set Methods boolean add (Object obj) – adds object and returns true if obj is not already in the set. returns false and doesn’t change the set if the element already exists. boolean contains(Object obj) – returns true is obj is in the set, false otherwise. boolean remove (Object obj) – removes obj from the set and returns true if obj was in the set; returns false otherwise. int size() – returns the number of elements in the set. Iterator iterator() – returns an iterator over the elements.
18
The HashSet Class implements set items are not stored in a particular order, and therefore do not need to be comparable. Methods for HashSet are same as Set Iterator, however, returns the elements in no particular order, and does not guarantee that the order will stay the same overtime. HashSet is implemented with a hash table. Has a O(1) run time for add remove and contains.
19
The TreeSet Class Implements the SortedSet interface guarantees that the sorted set will be in ascending order. Uses compareTo, so items of TreeSet are Comparable. They are mutally comparable: using compareTo will not throw a ClassCastException for any pair of elements in the set. Methods: same as Set: add, contains, remove size and iterator. iterator() for a TreeSet returns elements in ascending order. Implemented with a balanced tree, therefore O(logN) run time for add, remove and contains.
20
TreeSet / HashSet Example Set s = new hashSet(); s.add(“Mary”); s.add(“Joan”); s.add(“Mary”); s.add(“Dennis”); S.O.P(“The size of the set is “+ s.size()); Iterator itr = s.iterator(); while (itr.hasNext()) System.out.print((String ) itr.next() + “ “); System.out.println(); Set t = new TreeSet(s); itr = t.iterator(); while (itr.hasNext()) System.out.print ((String ) itr.next() + “ “);
21
Comparing TreeSet and HashSet If ordering of elements is important, use TreeSet If not, use HashSet because the runtime of the operations is faster. After creating an iterator for either Set implmentation don’t modify the set with any method other than itr.remove(). You will generate an error if you do. The set implementartions do not allow duplicates.
22
The Map Interface map is a collection of key-to-value mappings, where both key and value can be any object A map cannot contain duplicate keys, which means that each key maps to exactly 1 object. Different keys can map to the same object.
23
Map Methods Object put (Object key, Object value) – associates key with value and inserts the pair in the map. If the map already contained a mapping for this key, the old value is replaced. The previous value is returned, or null if no previous value existed. Object get (Object key)- Returns the value associated with the key. Returns null if the map does not contain the key. So, getting a null could mean that key maps to null, or that the key does not exist… so…
24
Map Methods… boolean containsKey(Object key) – returns true if the map contains a mapping for key, false otherwise. Object remove (Object key) – removes the mapping for key from this map if present. Returns the previous value associated with key, or null.. if there was no mapping of key or null if the key was associated with null. int size() – returns the number of key /value mappings in the map. Set keySet() – Returns the set of keys contained in the map… no duplication remember?
25
The HashMap Class Implements the Map interface with a HashTable. Again, no order. HashMap provides O(1) run times for get and put operations. Methods are same as those of map.
26
The TreeMap Class implements the SortedMap interface using a balanced binary search tree. Guarantees ascending key order based on the ordering of the key class. Guarantees O(log n) performance for the containsKey, get and put operations. Methods same as Map.
27
Iterating over a map Map iteration is not tested, because they do not provide you with a map iterator…But…This will iterate over the set of keys for mapping m: for (Iterator i = m.keySet().iterator(); i.hasNext();) System.out.print (i.next());
28
Example 1 Map employeeMap = new HashMap(); Emplyee emp; for (int i = 1; i <= NUM_EMPS; i++) { emp = new Employee(); emp.setName(..); emp.setSalary(…); emp.setID(“E”+ i); emplyeeMap.put(emp.getID(), emp); } System.out.println (employeeMap.get(“E4”);
29
Example 2 Map h = new HashMap(); h.put (“Othello”, “green”); h.put (“MacBeth”, “red”); h.put(“Hamlet”, “blue”); if (!h.containsKey(“Lear”)) h.put(“Lear”, “black”); Map t = new TreeMap(h); System.out.println (h.keySet()); System.out.println (t.keySet());
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.