1 / 64

Java Programming

Java Programming. The Collections Framework. Java Collections Framework. The Java Collections Framework defines classes and interfaces. The base class of this framework is Collection. Java Collections Framework.

bob
Download Presentation

Java Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Programming The Collections Framework

  2. Java Collections Framework • The Java Collections Framework defines classes and interfaces. The base class of this framework is Collection.

  3. Java Collections Framework • Collection: a group of elements. Supported operations are the most general kind that all sets and lists support. • Set: a collection that • cannot contain duplicate elements • elements are not ordered • elements do not have a position. • List: a collection that • can contain duplicate elements. • elements are ordered • elements have a position.

  4. Java Collection • public interface Collection<E> extends Iterable<e> { • intsize(); • booleanisEmpty(); • booleancontains(Object element); • booleanadd(E element); //optional • booleanremove(Object element); //optional • Iterator<E> iterator(); • booleancontainsAll(Collection<?> c); • booleanaddAll(Collection<? extends E> c); //optional • booleanremoveAll(Collection<?> c); //optional • booleanretainAll(Collection<?> c); //optional • void clear(); //optional • // others omitted • }

  5. Collection Methods • int size(): • returns the number of elements in the collection • booleanisEmpty(): • returns true if the collection is empty and false otherwise • boolean contains(Object x): • returns true if the collection contains the specified element and false otherwise • boolean add(E e): • Ensures that the collection contains the specified element. Returns true if the collection changed as a result and false otherwise.

  6. Collection Methods • boolean remove(Object e): • removes a single instance of the specified element if it is contained. Returns true if the collection was changed as a result and false otherwise. • booleancontainsAll(Collection<?> c): • returns true if the collection is empty and false otherwise • boolean contains(Object x): • returns true if the collection contains the specified element and false otherwise • boolean add(E e): • Ensures that the collection contains the specified element. Returns true if the collection changed as a result and false otherwise. • void clear(): • Removes all of the elements from this collection

  7. Collection Methods • booleanaddAll(Collection<? extends E> c) • Adds all of the elements in the specified collection to this collection. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. • booleanremoveAll(Collection<?> c) • Removes all of this collection's elements that are also contained in the specified collection. After this call returns, this collection will contain no elements in common with the specified collection. • booleanretainAll(Collection<?> c) • Retains only the elements in this collection that are contained in the specified collection. Removes from this collection all of its elements that are not contained in the specified collection

  8. Iterator • Iterator<E> iterator() • returns an iterator over the elements in this collection. • The Iterator interface defines 3 methods • booleanhasNext() • returns true if the iteration has more elements • E next() • returns the next element in the iteration • void remove() • removes from the underlying collection the last element returned by the iterator public interface Iterator<E> { public booleanhasNext(); public E next(); public void remove(); }

  9. Using the Collection interface public void example(Collection<String> names) { names.clear(); names.add(“China”); names.add(“America”); names.add(“Canada”); names.add(“France”); boolean a = names.contains(“Israel”); boolean b = names.remove(“France”); boolean c = names.isEmpty(); int s = names.size(); Iterator<String> it = names.iterator(); while(it.hasNext()) { System.out.println(it.next()); } for(String name : names) { System.out.println(name); } }

  10. Implementing Collection Methods • Consider the two methods contains and containsAll. • containsAll can be implemented in terms of contains. public booleancontainsAll(Collection<?> other) { for(Object element : other) { if(!contains(element)) return false; } return true; }

  11. Collection implementation • Some Collection methods can be written in terms of other Collection methods. • boolean contains(Object c); • booleancontainsAll(Collection<?> c); • booleanaddAll(Collection<? extends E> c); //optional • booleanremoveAll(Collection<?> c); //optional • booleanretainAll(Collection<?> c); //optional • void clear(); //optional • We should write one class that implements these methods. • This class would be abstract. • No subclass would have to provide these methods. • Each subclass must provide all other Collection methods.

  12. AbstractCollection public abstract class AbstractCollection<E> implements Collection<E> { public boolean contains(Object e) { // This code should check for null-valued ‘e’ but doesn’t. Just add an extra case Iterator<E> items = iterator(); while(items.hasNext()) { if(e.equals(items.next()) return true; } return false; } public booleancontainsAll(Collection<?> c) { for(Object item : c) { if(!contains(item)) return false; } return true; } public booleanaddAll(Collection<? extends E> c) { boolean changed = false; for(E item : c) { changed = changed || add(item); } return changed; } // other methods not listed. }

  13. List ADT • A list is a sequence of elements • A0, A1, A2, …, AN-1 • Properties • The subscript indicates the position of an element • The size of a list is the number of elements in the list • Each element in a list is of the same type. • List is-aCollection that includes support for • Positional access: obtains an element from position • Searching: returns the position of an element • Ranged viewing: returns sub-lists based on positions of elements

  14. Java List • public interface List<E> extends Collection<E> { • // Positional access • E get(int index); • E set(int index, E element); //optional • void add(int index, E element); //optional • E remove(int index); //optional • booleanaddAll(int index, Collection<? extends E> c); //optional • // Search • intindexOf(Object o); • intlastIndexOf(Object o); • Iteration ListIterator<E> listIterator(); • ListIterator<E> listIterator(int index); • // Range-view • List<E> subList(intfrom, int to); • }

  15. Using the List interface • public void example(List<String> names) { • names.add(“Rams”); • names.add(“Vikings”); • names.add(“Packers”); • names.add(“Bears”); • boolean a = names.contains(“Rams”); • boolean b = names.remove(“Vikings”); • boolean c = names.isEmpty(); • int s = names.size(); • Iterator<String> it = names.iterator(); • while(it.hasNext()) { • System.out.println(it.next()); • } • for(String name : names) { • System.out.println(name); • } • String n1 = names.get(0); • String n2 = names.set(0, “Cardinals”); • names.add(0, “Lions”); • int i1 = names.indexOf(“Bears”); • List<String> nfc = names.sublist(0, 3); • }

  16. Implementing Collection Methods • Consider the two methods add(int,E) and addAll(int, Collection) • addAll can be implemented in terms of add • Since some List methods can be implemented in terms of other List methods, write an abstract list class. public booleanaddAll(int index, Collection<? extends E> other) { boolean modified = false; for(E e : c) { add(index++, e); modified = true; } return modified; }

  17. Concrete Implementation • There must be a concrete class that implements the List interface. • There may be more than one implementation. • There are two basic ways to implement: • ArrayList: Store the elements in an array. • LinkedList: Store the elements in linked nodes

  18. Class Diagram for Lists

  19. ArrayList • ArrayList is in the java.util package. An ArrayList implements List with a backing array. • An ArrayListis not an array. • An ArrayListcontains an array. • The ArrayList has a capacity (the array size) • The ArrayList has a size (the number of elements in the list)

  20. Using the List interface : part 2 • public void example() { • List<String> names = new ArrayList(); • names.add(“Rams”); • names.add(“Vikings”); • names.add(“Packers”); • names.add(“Bears”); • boolean a = names.contains(“Rams”); • boolean b = names.remove(“Vikings”); • boolean c = names.isEmpty(); • int s = names.size(); • String n1 = names.get(0); • String n2 = names.set(0, “Cardinals”); • names.add(0, “Lions”); • int i1 = names.indexOf(“Bears”); • }

  21. ArrayList implementation

  22. ArrayList implementation

  23. ArrayList implementation

  24. ArrayList Time Complexity

  25. LinkedList • A LinkedList is a concrete implementation of List • Uses nodes to hold elements and to impose a linear structure on the elements. A node knows the node that succeeds it in the list (the ‘next’ node). • Variations of the linked list can be useful. • The LinkedList class in Java is a doubly-linked list. • We will start with a singly-linked list.

  26. Using the List interface : part 3 • public void example() { • List<String> names = new SinglyLinkedList(); • names.add(“Rams”); • names.add(“Vikings”); • names.add(“Packers”); • names.add(“Bears”); • boolean a = names.contains(“Rams”); • boolean b = names.remove(“Vikings”); • boolean c = names.isEmpty(); • int s = names.size(); • String n1 = names.get(0); • String n2 = names.set(0, “Cardinals”); • names.add(0, “Lions”); • int i1 = names.indexOf(“Bears”); • }

  27. SinglyLinkedList

  28. SinglyLinkedList

  29. SinglyLinkedList

  30. SinglyLinkedList Iterator Code

  31. SinglyLinkedList Time Complexity

  32. DoublyLinkedList • A DoublyLinkedList is a concrete implementation of List • Uses nodes to hold elements and to impose a linear structure on the elements. • A node knows the preceding and succeeding nodes.

  33. DoublyLinkedList Time Complexity

  34. Stack<E> • A stack is a very simple linear data type that follows the last-in-first-out (LIFO) principle. • E push(E element): • means add the element to the stack. Also returns the added element. • E pop(): • means remove the last pushed element • E top(): • return the last pushed element

  35. Stack<E> • The Stack class in Java is odd. It is a subclass of List that simply adds methods named push, pop, top and a few others. • Since it is a subclass of List, a Stack can be used as a list and violate the LIFO principle. • This is not too good of a design, but it is convenient for programmers writing the Stack class. • The Stack uses a sequential implementation • We will write our own implementation

  36. Stack<E> public interface Stack<E> extends Collection<E> { public E top(); public E pop(); public E push(E element); } This is an example of the adapter pattern. An adapter, or wrapper, makes one object behave like another. public class ArrayStack<E> extends AbstractCollection<E> implements Stack<E> { private ArrayList<E> stack; public int size() { return stack.size(); } public Iterator<E> iterator() { return stack.iterator(); } public E top() { if(isEmpty()) throw new EmptyStackException(); return stack.get(stack.size()-1); } public E push(E e) { stack.add(e); return e; } public E pop() { if(isEmpty()) throw new EmptyStackException(); return stack.remove(stack.size()-1); } }

  37. Queue Interface • A queue is a very simple linear data type that follows the first-in-first-out (FIFO) principle. • E enqueue(E element): • means addthe element to the queue. Also returns the added element. • E dequeue() • removes and returns the element that was added before all others • E front(): • returns the element that was added before all others

  38. Queue<E> public interface Queue<E> extends Collection<E> { public E font(); public E dequeue(); public E enqueue(E element); } public class ArrayQueue<E> extends AbstractCollection<E> implements Stack<E> { private ArrayList<E> queue; public int size() { return queue.size(); } public Iterator<E> iterator() { return queue.iterator(); } public E front () { if(isEmpty()) throw new EmptyStackException(); return queue.get(0); } public E enqueue(E e) { queue.add(size(), e); return e; } public E dequeue() { if(isEmpty()) throw new EmptyStackException(); return queue.remove(0); } }

  39. Map<K,V> • A map associates keys with values. • A map cannot contain duplicate keys • Each key can map to at most one value. • Supports the following basic methods • V put(K key, V value) • associates the key with the value. Returns the object previously associated with the key (null if none). • V get(K key) • returns the value associated with the key. Returns null if the key is not in the map • V remove(K key) • removes any association between the key and value. Returns the value that was associated with the key.

  40. Map<K,V> public interface Map<K,V> { int size(); booleanisEmpty(); booleancontainsKey(Object key); booleancontainsValue(Object value); V get(Object key); V put(K key, V value); V remove(Object key); void putAll(Map<? extends K, ? extends V> m); void clear(); Set<K> keySet(); Collection<V> values(); Set<Map.Entry<K, V>> entrySet(); interface Entry<K,V> { K getKey(); V getValue(); V setValue(V value); boolean equals(Object o); inthashCode(); } boolean equals(Object o); inthashCode(); }

  41. Selected Map<K,V> methods • booleancontainsKey(Object key) • Returns true if the map contains the key and false otherwise • booleancontainsValue(Object value) • Returns true if the map contains one or more keys to the specified value. • V get(Object key) • Returns the value associated with the specified key • V put(K key, V value) • Associates the key with the value. Returns the value previously associated with key or null of none. • V remove(Object key) • Removes the key from the map • void putAll(Map<? extends K, ? extends V> otherMap) • performs a put on every element of otherMap • void clear() • removes all key-value mappings

  42. Selected Map<K,V> methods • Set<K> keySet() • returns a set of the keys • Collection<V> values() • returns a collection of the values • Set<Map.Entry<K, V>> entrySet() • returns a set of entries • Entry<K,V> is a nested inner interface. Represents one key-value association. • K getKey() • returns the key of the Entry • V getValue() • returns the value of the Entry • V setValue(V value) • Modifies the value mapped to by the key. Returns the previous mapping

  43. Using a Map public void example(Map<String, Integer> map) { map.put(“A”, 1); map.put(“B”, 2); map.put(“C”, 3); Integer x = map.get(“C”); Integer y = map.get(“A”); Integer z = map.get(new Integer(3)); intsize = map.size(); // How to print the values in the map? // How to print the keys in the map? }

  44. public abstract class AbstractMap<K,V> implements Map<K,V> { protected AbstractMap() { } public booleanisEmpty() { return size() == 0; } public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } public static class SimpleEntry<K,V> implements Entry<K,V> { private final K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } } }

  45. public class ListMap<K,V> extends AbstractMap<K,V> { private List<Entry<K,V>> entries; public ListMap() { entries = new LinkedList<>(); } public ListMap(Map<K,V> source){ entries = new LinkedList<>(); for(K key : source.keySet()) { put(key, source.get(key)); } } // this is linear search...O(n) private Entry<K,V> getEntry(Object key) { for(Entry<K,V> e : entries) { if(e.getKey().equals(key)) return e; } return null; } @Override public booleancontainsKey(Object key) { return getEntry(key) != null; } @Override public V get(Object key) { Entry<K,V> entry = getEntry(key); if(entry != null) { return entry.getValue(); } return null; }

  46. public V put(K key, V value) { Entry<K,V> entry = getEntry(key); if(entry != null) { return entry.setValue(value); } else { entries.add(0, new AbstractMap.SimpleEntry(key,value)); return value; } } public V remove(Object key) { Entry<K,V> entry = getEntry(key); if(entry != null) { entries.remove(entry); return entry.getValue(); } else { return null; } } public booleancontainsValue(Object value) { for(Entry e : entries) { if(e.getValue().equals(value)) return true; } return false; } public void clear() { entries.clear(); } public int size() { return entries.size(); } // several other methods are not shown here }

  47. What is a Hashtable? • The previous implementation adapts a LinkedList to perform as a Map. • The LinkedList adapter is easy to write. • The LinkedList adapter is inefficient. Finding a key in the list is linear: O(n) • A Hashtableis a map that stores key-value pairs in an array using a hashing strategy. • A key is converted to an array index using a hash function. The hash function is fast therefore finding an entry is fast. • In other words: given a key K we know what the index of K will be and therefore don’t need to search (although some small amount of searching may be necessary).

  48. Hashtable Example • Hashtable of character/integers • The hashtable is an array of 7 • The hashtable capacity is 7 • Initially, the hashtable size is 0 • Insert characters into the table. • A single character is a key. • The hash function must take a character as input and convert it into a number between 0 and 6. • Hash function • Let P be the position of the character in the English alphabet (starting with 1). • Use h(K) = (P % 7) as the hash function

  49. Hashtable Example • Consider inserting the following data into the table. Subscripts are used to denote the position of the character in the alphabet. • put(B2, 102) • put(S19, 3) • put(J10, -12) • put(N14, 44) • put(X24, 85) // interesting • put(W23, -33) • put(B2, -101) • get(X24) • get(W23) N:44 B:-101 B:102 J:-12 X:85 S:3 W:-33

  50. Collisions • A collision occurs when two-or-more different keys map to the same array index. • When a collision occurs, a collision resolution policy will determine how to resolve the collision • The load factor is defined as the size/capacity. The odds of a collision increase with increasing load factor. • Two collision resolution policies: • Open Addressing: look for an open slot using a pre-determined sequence of probes. • Separate Chaining: keep a list of key/value pairs in a slot such that one slot can contain multiple key values.

More Related