29
Collections Mrs. C. Furman April 21, 2009

Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

Embed Size (px)

Citation preview

Page 1: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

Collections

Mrs. C. Furman

April 21, 2009

Page 2: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

Collection Classes

ArrayList and LinkedList implements List

HashSet implements Set

TreeSet implements SortedSet

HashMap implements Map

TreeMap implements SortedMap

Page 3: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 4: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 5: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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()

Page 6: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 7: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

List Interface

Methods of List:boolean add(Object obj) – adds element at endint size() – returns number of elementsObject get (int index) – returns the Object at the

indexObject 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.

Page 8: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 9: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

ArrayList

Methods for ArrayList:ArrayList() – constructs an empty list.. only stores Objectsvoid 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.

Page 10: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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 < 0 || index >= size()

add can use the index that is equal to size… soindex < 0 || index > size() is out of bounds.

Page 11: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 12: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 13: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

ArrayList vs. LinkedListInsert at front add(0, obj)

O(n) shifts all the element

addFirst (obj)

O(1).

Insert at End add(obj)

O(1)

O(n) – adding n elements

add(obj)

O(1)

Delete at front remove(0)

O(n) – shifting n elements down

removeFirst()

O(1)

Delete at End remove (size() -1 )

O(1)

removeLast()

O(1)

Insert in middle add(Index, obj)

O(1) – find the spot

O(n) – insert the element.

itr.add()

O(n) – find the spot

O(1) – insert.

Page 14: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

Delete in middle remove (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 1st 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

Page 15: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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

Page 16: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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!!

Page 17: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 18: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 19: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 20: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

TreeSet / HashSet ExampleSet 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() + “ “);

Page 21: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 22: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 23: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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…

Page 24: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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?

Page 25: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 26: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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.

Page 27: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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());

Page 28: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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”);

Page 29: Collections Mrs. C. Furman April 21, 2009. Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet

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());