1 interfaces in java’s collection framework rick mercer

21
1 Interfaces in Java’s Collection Framework Rick Mercer

Upload: alberta-green

Post on 17-Jan-2016

231 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Interfaces in Java’s Collection Framework Rick Mercer

1

Interfaces in Java’sCollection Framework

Rick Mercer

Page 2: 1 Interfaces in Java’s Collection Framework Rick Mercer

2

Java's Collection Framework

Java's Collection Framework— Unified architecture for representing and manipulating

collections Collection framework contains

— Interfaces (ADTs): specification not implementation— Concrete implementations as classes— Polymorphic Algorithms to search, sort, find, shuffle, ...

Algorithms are polymorphic: — the same method can be used on many different

implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

Page 3: 1 Interfaces in Java’s Collection Framework Rick Mercer

3

Core Collection interfaces in java.util

Image from the Java Tutorial

Set, List, and Queue extend the Collection interface — If you implement Set, in addition to all of Set’s methods,

all Collection methods must also be implemented

BTW: Collection<E> extends Iterable<E>

Page 4: 1 Interfaces in Java’s Collection Framework Rick Mercer

4

interface Collection Bags (multi-sets) should implement Collection directly

boolean add(E e) boolean addAll(Collection<? extends E> c) void clear() boolean contains(Object o) boolean containsAll(Collection<?> c) boolean equals(Object o) int hashCode() boolean isEmpty() Iterator<E> iterator() boolean remove(Object o) boolean removeAll(Collection<?> c) boolean retainAll(Collection<?> c) int size() Object[] toArray() <T> T[] toArray(T[] a)

Page 5: 1 Interfaces in Java’s Collection Framework Rick Mercer

5

List<E> an ADT written as a Java interface

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

The List interface is implemented by these three collection classes— ArrayList<E>— LinkedList<E>— Vector<E>

Page 6: 1 Interfaces in Java’s Collection Framework Rick Mercer

6

// Interface name: List // Three classes that implement the List interface: List<String> bigList = new ArrayList<String>(); List<String> littleList = new LinkedList<String>(); List<String> sharedList = new Vector<String>();

// All three have an add method bigList.add("in array list"); littleList.add("in linked list"); sharedList.add("in vector");

// All three have a get method assertEquals("in array list", bigList.get(0)); assertEquals("in linked list", littleList.get(0)); assertEquals("in vector", sharedList.get(0));

Can treat all three (and more) as a List

Page 7: 1 Interfaces in Java’s Collection Framework Rick Mercer

7

interface Iterator

Iterators provide a general way to traverse all elements in a collection

ArrayList<String> list = new ArrayList<String>(); list.add("1-FiRsT"); list.add("2-SeCoND"); list.add("3-ThIrD"); Iterator<String> itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next().toLowerCase()); }

Output1-first2-second3-third

Page 8: 1 Interfaces in Java’s Collection Framework Rick Mercer

8

The actual interface

public interface Iterator<E> { // Returns true if the iteration has more elements. boolean hasNext();

//Returns the next element in the iteration. E next(); // Removes from the underlying collection the last element // returned by the iterator (optional operation). void remove(); }

Page 9: 1 Interfaces in Java’s Collection Framework Rick Mercer

9

Algorithms

Java has polymorphic algorithms to provide functionality for different types of collections

Methods use interfaces to Sort any List — Sorting (e.g. sort)— Shuffling (e.g. shuffle)— Routine Data Manipulation (e.g. reverse, addAll)— Searching (e.g. binarySearch)— Composition (e.g. frequency)— Finding Extreme Values (e.g. max)

Page 10: 1 Interfaces in Java’s Collection Framework Rick Mercer

10

Before looking at Collections.java. some Additional Generics

To specify additional interfaces that must be implemented, use the & character, as in:

<U extends Number & MyInterface>

In generics, an unknown type is represented by the wildcard character “?”

containsAll(Collection<?> c)

The receiver must be a superclass (or the same type) of the type of elements being added

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html

Page 11: 1 Interfaces in Java’s Collection Framework Rick Mercer

11

Can add <String> to <Objects> or to <String>

final class String extends ObjectList<String> a = new ArrayList<String>();a.add("Z");a.add("A");List<Object> b = new ArrayList<Object>();b.add("Y");b.add("B");b.addAll(a); System.out.println(a);System.out.println(b);// a.addAll(a) is okay, // but this is an error: a.addAll(b);

Page 12: 1 Interfaces in Java’s Collection Framework Rick Mercer

12

class Collections has many static methods

List<String> a = new ArrayList<String>();a.add("Z");a.add("A");a.add("M");a.add("T");a.add("G");System.out.println(a);System.out.println(Collections.min(a));System.out.println(Collections.max(a));Collections.sort(a);System.out.println(a);Collections.shuffle(a);System.out.println(a);

[Z, A, M, T, G]

A

Z

[A, G, M, T, Z]

[G, M, T, Z, A]

public static <T extendsObject & Comparable<? super T>>T min(Collection<? extends T> coll)

// Ugly …

Page 13: 1 Interfaces in Java’s Collection Framework Rick Mercer

13

TreeSet implements Set

Set<E> collections with no duplicates— More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)

— Has the same methods as Collection, but intended to have different meanings

public interface Set<E> extends Collection<E> { boolean add(E o); // Do not allow duplicates

Page 14: 1 Interfaces in Java’s Collection Framework Rick Mercer

14

Set and SortedSet

The Set<E> interface extends CollectionTwo classes that implement Set<E>

— TreeSet: values stored in order, O(log n)— HashSet: values in a hash table, no order, O(1)

SortedSet extends Set by adding methods E

first(), SortedSet<E> tailSet(E fromElement),

SortedSet<E> headSet(E fromElement), E last(), SortedSet<E> subSet(E fromElement, E toElement)

Page 15: 1 Interfaces in Java’s Collection Framework Rick Mercer

15

Set or SortedSet?

Set<String> names = new TreeSet<String>();names.add("Sandeep");names.add("Chris");names.add("Kim");names.add("Chris"); // not addednames.add("Devon");

for (String name : names) System.out.println(name);

Change to HashSet

Page 16: 1 Interfaces in Java’s Collection Framework Rick Mercer

16

The Map Interface (ADT)

Map describes a type that stores a collection of elements that consists of a key and a value

A Map associates (maps) a key the it's valueThe keys must be unique

— the values need not be unique— put destroys one with same key

Page 17: 1 Interfaces in Java’s Collection Framework Rick Mercer

17

Map Operations

Java's HashMap<K, V>— public V put(K key, V value)

• associates key to value and stores mapping— public V get(Object key)

• associates the value to which key is mapped or null— public boolean containsKey(Object key)

• returns true if the Map already uses the key— public V remove(Object key)

• Returns previous value associated with specified key, or null if there was no mapping for key.

— Collection<V> values() • get a collection you can iterate over

Page 18: 1 Interfaces in Java’s Collection Framework Rick Mercer

18

Sample Code

Map<Integer, String> map = new HashMap<Integer, String>();

map.put(2, "Ali");map.put(1, "Jaime");map.put(3, "Alex");map.put(1, "Dylan"); // Wipes out oldSystem.out.println(map);System.out.println(map.keySet());System.out.println(map.values());

Page 19: 1 Interfaces in Java’s Collection Framework Rick Mercer

19

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

Page 20: 1 Interfaces in Java’s Collection Framework Rick Mercer

20

ArrayBlockingQueue<E> a FIFO queue

ArrayBlockingQueue<Double> numberQ = new ArrayBlockingQueue<Double>(40);numberQ.add(3.3);numberQ.add(2.2);numberQ.add(5.5);numberQ.add(4.4);numberQ.add(7.7);

assertEquals(3.3, numberQ.peek(), 0.1);assertEquals(3.3, numberQ.remove(), 0.1);assertEquals(2.2, numberQ.remove(), 0.1);assertEquals(5.5, numberQ.peek(), 0.1);assertEquals(3, numberQ.size());

Page 21: 1 Interfaces in Java’s Collection Framework Rick Mercer

21

Another use of interfaces

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.

http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html