java's collection framework - university of arizona · 2016. 4. 26. · 2 java's...

26
1 Java's Collection Framework

Upload: others

Post on 21-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

1

Java's Collection Framework

Page 2: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

2

Java's Collection Framework

w Collection framework— Unified architecture for representing and manipulating

collectionsw Java's collection framework contains

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

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

Page 3: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

3

Collection interfaces in java.util

Image from the Java Tutorial

Page 4: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

4

Abstract Data Type

wAbstract 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

wWhich Java construct nicely specifies ADTs?

Page 5: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

5

Collection Classes

wA collection class the can be instantiated— implements an interface as a Java class— implements all methods of the interface— selects appropriate instance variables

wJava has many collection classes including:— ArrayList<E> LinkedList<E>— LinkedBlockingQueue<E> ArrayBlockingQueue<E>— Stack<E> — HashSet<E> TreeSet<E>— HashMap<K,V> TreeMap<K,V>

Page 6: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

6

Common Functionality

wCollection 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

Page 7: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

7

The Collection Interface

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

wSome classes implementing Collection— allow duplicate elements; others do not — keeps elements ordered; others do not

Page 8: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

8

Collection method signatures

wThe methods of interface Collectionhttp://java.sun.com/javase/7/docs/api/java/util/Collection.html

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

Page 9: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

9

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

Page 10: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

10

Why have interface Collection?

wWith this method, we can iterate over all Collections using hasNext and NextIterator<E> iterator()

wWith this method, we can find out if all the elements in a set are in a list or queue, or …

boolean containsAll(Collection<?> c)

Page 11: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

11

interface List extends interface Collection

wList: 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

Page 12: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

12

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

Page 13: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

13

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, addAll, indexOf, isEmpty,

remove, toArray

w Some implementing classes in java.util: — ArrayList<E>, LinkedList<E>, Stack<E>,Vector<E>, many more

Page 14: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

14

import java.util.*; // For List, ArrayList, Linked ... import static org.junit.Assert.*;import org.junit.Test;

public class ThreeClassesImplementList {

@Testpublic void showThreeImplementationsOfList() {

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

// All three have an add methodaList.add("in array list");elList.add("in linked list");sharedList.add("in vector");

// All three have a get methodassertEquals("in array list", aList.get(0));assertEquals("in linked list", elList.get(0));assertEquals("in vector", sharedList.get(0));

}}

Page 15: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

15

List<Integer> arrayL = new ArrayList<Integer>();List<Integer> linkedL = new LinkedList<Integer>();for (int num = 1; num <= 12; num += 2) {

arrayL.add(num);linkedL.add(num + 1);

}Iterator<Integer> arrayItr = arrayL.iterator();Iterator<Integer> linkedItr = linkedL.iterator();

while (arrayItr.hasNext())System.out.print(arrayItr.next() + " ");

System.out.println();while (linkedItr.hasNext())

System.out.print(linkedItr.next() + " ");

Output:1 3 5 7 9 11 2 4 6 8 10 12

Iterate over different lists the same way

Page 16: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

16

List<Integer> arrayL = new ArrayList<Integer>();List<Integer> linkedL = new LinkedList<Integer>();for (int num = 1; num <= 12; num += 2) {

arrayL.add(num);linkedL.add(num + 1);

}

for (Integer theInt : arrayL)System.out.print(theInt + " ");

System.out.println();

for (Integer theInt : linkedL)System.out.print(theInt + " ");

Output is the same, no iterators needed:1 3 5 7 9 11 2 4 6 8 10 12

The enhanced for loop

Page 17: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

17

Polymorphism via interfaces

wThe 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

wThis is polymorphism via interfaces

Page 18: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

18

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 19: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

19

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 20: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

20

TreeSet implements Set

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

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

Page 21: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

21

TreeSet elements are in order

SortedSet<Integer> set = new TreeSet<Integer>();set.add(7);set.add(7);set.add(2);set.add(7);set.add(8);set.add(9);

System.out.println(set.toString());System.out.println(set.subSet(1, 8));System.out.println(set.tailSet(8));System.out.println(set.headSet(8));

[2, 7, 8, 9][2, 7][8, 9][2, 7]

Page 22: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

22

HashSet elements are not in order

Set<String> names = new HashSet<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

Page 23: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

23

The Map Interface (ADT)

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

wA Map associates (maps) a key the it's valuewThe keys must be unique

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

wConcrete classes in java.util— HashMap<K, V> and TreeMap<K, V>

Page 24: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

24

Map Operations

w java.util.HashMap<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 containsKey(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> keySet() • get a collection you can iterate over

Page 25: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

25

Using a Map

Map<String, BankAccount> aMap= new TreeMap<String, BankAccount>();BankAccount acct1 = new BankAccount("Jessica", 500.00);BankAccount acct2 = new BankAccount("Alex", 400.00);BankAccount acct3 = new BankAccount("Anthony", 300.00);BankAccount acct4 = new BankAccount("Danny", 200.00);

aMap.put(acct1.getID(), acct1);aMap.put(acct2.getID(), acct2);aMap.put(acct3.getID(), acct3);aMap.put(acct4.getID(), acct4);

// Check out the keys and the value in aMapCollection<String> keys = aMap.keySet();System.out.println(keys);Collection<BankAccount> values = aMap.values();System.out.println(values);

Output[Alex, Anthony, Danny, Jessica][Alex $400.0, Anthony $300.0, Danny $200.0, Jessica $500.0]

Page 26: Java's Collection Framework - University of Arizona · 2016. 4. 26. · 2 Java's Collection Framework w Collection framework — Unified architecture for representing and manipulating

26

Using a Map

// over write a value, put returns old valueSystem.out.println(aMap.put("Jessica", new BankAccount("New", 0.99)));

OutputJessica $500.00

// put in a new key, get null backSystem.out.println(aMap.put("NewKey", new BankAccount("NewValue", 0)));

Outputnull

// successful remove return the removed valueSystem.out.println(aMap.remove("Jessica"));

OutputNew $0.99