Javas Collection Framework 1 Javas Collection Framework w

  • Slides: 26
Download presentation
Java's Collection Framework 1

Java's Collection Framework 1

Java's Collection Framework w Collection framework — w Java's collection framework contains — —

Java's Collection Framework w Collection framework — w Java's collection framework contains — — — w Unified architecture for representing and manipulating collections Interfaces (ADTs): specification not implementation Concrete implementations as classes Polymorphic Algorithms to search, sort, find, shuffle, . . . The algorithms are polymorphic: — the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. 2

Collection interfaces in java. util Image from the Java Tutorial 3

Collection interfaces in java. util Image from the Java Tutorial 3

Abstract Data Type w Abstract data type (ADT) is a specification of the behaviour

Abstract Data Type w Abstract data type (ADT) is a specification of the behaviour (methods) of a type Specifies method names to add, remove, find — Specifies if elements are unique, indexed, accessible from only one location, mapped, . . . — An ADT shows no implementation — • no structure to store elements, no implementations w Which Java construct nicely specifies ADTs? 4

Collection Classes w A collection class the can be instantiated implements an interface as

Collection Classes w A collection class the can be instantiated implements an interface as a Java class — implements all methods of the interface — selects appropriate instance variables — w Java has many collection classes including: — — — Array. List<E> Linked. Blocking. Queue<E> Array. Blocking. Queue<E> Stack<E> Hash. Set<E> Tree. Set<E> Hash. Map<K, V> Tree. Map<K, V> 5

Common Functionality w Collection classes often have methods for Adding objects — Removing an

Common Functionality w Collection classes often have methods for Adding objects — Removing an object — Finding a reference to a particular object — • We can then send messages to the object still referenced by the collection 6

The Collection Interface w interface Collection abstractly describes a bag, or multi-set w Some

The Collection Interface w interface Collection abstractly describes a bag, or multi-set w Some classes implementing Collection allow duplicate elements; others do not — keeps elements ordered; others do not — 7

Collection method signatures w The methods of interface Collection http: //java. sun. com/javase/7/docs/api/java/util/Collection. html

Collection method signatures w The methods of interface Collection http: //java. sun. com/javase/7/docs/api/java/util/Collection. html boolean add(E e) boolean add. All(Collection<? extends E> c) void clear() boolean contains(Object o) boolean contains. All(Collection<? > c) boolean equals(Object o) int hash. Code() boolean is. Empty() Iterator<E> iterator() boolean remove(Object o) boolean remove. All(Collection<? > c) boolean retain. All(Collection<? > c) int size() Object[] to. Array() 8

Why have interface Collection? w Collection allows different types of objects to be treated

Why have interface Collection? w Collection allows different types of objects to be treated the same w It is used to pass around collections of objects with maximum generality for example add. All(Collection<? extends E> c) — This method adds all of the elements in the specified collection in an appropriate way • Can add all elements of a List to a Queue, or • add all elements of a Set to a List, or • add all elements of one List to another List 9

Why have interface Collection? w With this method, we can iterate over all Collections

Why have interface Collection? w With this method, we can iterate over all Collections using has. Next and Next Iterator<E> iterator() w With this method, we can find out if all the elements in a set are in a list or queue, or … boolean contains. All(Collection<? > c) 10

interface List extends interface Collection w List: a collection where indexes matter — —

interface List extends interface Collection w List: a collection where indexes matter — — extends Collection so it has all of the methods of Collection Can decide where in the List elements are inserted 11

List<E>, an Abstract Data Type (ADT) written as a Java interface w List<E>: a

List<E>, an Abstract Data Type (ADT) written as a Java interface w List<E>: a collection with a first element, a last element, distinct predecessors and successors — — The user of this interface has precise control over where in the list each element is inserted duplicates that "equals" each other are allowed 12

List<E> w Users of the interface List<E> — — — have precise control over

List<E> w Users of the interface List<E> — — — have precise control over where in the list each element is inserted. allows programmers to access elements by their integer index (position in the list) search for elements in the list Can have duplicate elements (equals) Methods include: add, add. All, index. Of, is. Empty, remove, to. Array w Some implementing classes in java. util: — Array. List<E>, Linked. List<E>, Stack<E>, Vector<E>, many more 13

import java. util. *; // For List, Array. List, Linked. . . import static

import java. util. *; // For List, Array. List, Linked. . . import static org. junit. Assert. *; import org. junit. Test; public class Three. Classes. Implement. List { @Test public void show. Three. Implementations. Of. List() { // Interface name: List // Three classes that implement the List interface: List<String> a. List = new Array. List<String>(); List<String> el. List = new Linked. List<String>(); List<String> shared. List = new Vector<String>(); // All three have an add method a. List. add("in array list"); el. List. add("in linked list"); shared. List. add("in vector"); } } // All three have a get method assert. Equals("in array list", a. List. get(0)); assert. Equals("in linked list", el. List. get(0)); assert. Equals("in vector", shared. List. get(0)); 14

Iterate over different lists the same way List<Integer> array. L = new Array. List<Integer>();

Iterate over different lists the same way List<Integer> array. L = new Array. List<Integer>(); List<Integer> linked. L = new Linked. List<Integer>(); for (int num = 1; num <= 12; num += 2) { array. L. add(num); linked. L. add(num + 1); } Iterator<Integer> array. Itr = array. L. iterator(); Iterator<Integer> linked. Itr = linked. L. iterator(); while (array. Itr. has. Next()) System. out. print(array. Itr. next() + " "); System. out. println(); while (linked. Itr. has. Next()) System. out. print(linked. Itr. next() + " "); Output: 1 3 5 7 9 11 2 4 6 8 10 12 15

The enhanced for loop List<Integer> array. L = new Array. List<Integer>(); List<Integer> linked. L

The enhanced for loop List<Integer> array. L = new Array. List<Integer>(); List<Integer> linked. L = new Linked. List<Integer>(); for (int num = 1; num <= 12; num += 2) { array. L. add(num); linked. L. add(num + 1); } for (Integer the. Int : array. L) System. out. print(the. Int + " "); System. out. println(); for (Integer the. Int : linked. L) System. out. print(the. Int + " "); Output is the same, no iterators needed: 1 3 5 7 9 11 2 4 6 8 10 12 16

Polymorphism via interfaces w The previous slides shows different types treated as type List,

Polymorphism via interfaces w The previous slides shows different types treated as type List, all three — — implement interface List understand the same messages have different methods with the same names execute All classes have add, get, iterator w This is polymorphism via interfaces 17

Queue<E> boolean add(E e) Inserts e into this queue E element() Retrieves, but does

Queue<E> boolean add(E e) Inserts e into this queue E element() Retrieves, but does not remove, the head of this queue boolean offer(E e)Inserts e into this queue E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty E remove() Retrieves and removes the head of this queue 18

Array. Blocking. Queue<E> a FIFO queue Array. Blocking. Queue<Double> number. Q = new Array.

Array. Blocking. Queue<E> a FIFO queue Array. Blocking. Queue<Double> number. Q = new Array. Blocking. Queue<Double>(40); number. Q. add(3. 3); number. Q. add(2. 2); number. Q. add(5. 5); number. Q. add(4. 4); number. Q. add(7. 7); assert. Equals(3. 3, number. Q. peek(), 0. 1); assert. Equals(3. 3, number. Q. remove(), 0. 1); assert. Equals(2. 2, number. Q. remove(), 0. 1); assert. Equals(5. 5, number. Q. peek(), 0. 1); assert. Equals(3, number. Q. size()); 19

Tree. Set implements Set w Set<E> An interface for collections with no duplicates. More

Tree. Set implements Set w Set<E> An interface for collections with no duplicates. More formally, sets contain no pair of elements e 1 and e 2 such that e 1. equals(e 2) w Tree. Set<E>: This class implements the Set interface, backed by a balanced binary search tree. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements as defined by Comparable<T> 20

Tree. Set elements are in order Sorted. Set<Integer> set = new Tree. Set<Integer>(); set.

Tree. Set elements are in order Sorted. Set<Integer> set = new Tree. Set<Integer>(); set. add(7); set. add(2); set. add(7); set. add(8); set. add(9); System. out. println(set. to. String()); System. out. println(set. sub. Set(1, 8)); System. out. println(set. tail. Set(8)); System. out. println(set. head. Set(8)); [2, [8, [2, 7, 8, 9] 7] 21

Hash. Set elements are not in order Set<String> names = new Hash. Set<String>(); names.

Hash. Set elements are not in order Set<String> names = new Hash. Set<String>(); names. add("Devon"); names. add("Sandeep"); names. add("Chris"); names. add("Kim"); names. add("Chris"); // not added for (String str : names) System. out. print(str + " "); Output: Sandeep Chris Devon Kim 22

The Map Interface (ADT) w Map describes a type that stores a collection of

The Map Interface (ADT) w Map describes a type that stores a collection of elements that consists of a key and a value w A Map associates (maps) a key the it's value w The keys must be unique the values need not be unique — put destroys one with same key — w Concrete classes in java. util — Hash. Map<K, V> and Tree. Map<K, V> 23

Map Operations w java. util. Hash. Map<K, V> — — — public V put(K

Map Operations w java. util. Hash. Map<K, V> — — — public V put(K key, V value) • associates key to value and stores mapping public V get(K key) • associates the value to which key is mapped or null public boolean contains. Key(K key) • returns true if the Map already uses the key public V remove(K key) public Collection<V> values() • get a collection you can iterate over public Collection<V> key. Set() • get a collection you can iterate over 24

Using a Map<String, Bank. Account> a. Map= new Tree. Map<String, Bank. Account>(); acct 1

Using a Map<String, Bank. Account> a. Map= new Tree. Map<String, Bank. Account>(); acct 1 = new Bank. Account("Jessica", 500. 00); acct 2 = new Bank. Account("Alex", 400. 00); acct 3 = new Bank. Account("Anthony", 300. 00); acct 4 = new Bank. Account("Danny", 200. 00); a. Map. put(acct 1. get. ID(), a. Map. put(acct 2. get. ID(), a. Map. put(acct 3. get. ID(), a. Map. put(acct 4. get. ID(), acct 1); acct 2); acct 3); acct 4); // Check out the keys and the value in a. Map Collection<String> keys = a. Map. key. Set(); System. out. println(keys); Collection<Bank. Account> values = a. Map. values(); System. out. println(values); Output [Alex, Anthony, Danny, Jessica] [Alex $400. 0, Anthony $300. 0, Danny $200. 0, Jessica $500. 0] 25

Using a Map // over write a value, put returns old value System. out.

Using a Map // over write a value, put returns old value System. out. println(a. Map. put("Jessica", new Bank. Account("New", 0. 99))); Output Jessica $500. 00 // put in a new key, get null back System. out. println(a. Map. put("New. Key", new Bank. Account("New. Value", 0))); Output null // successful remove return the removed value System. out. println(a. Map. remove("Jessica")); Output New $0. 99 26