Top Banner
12: Holding Your Objects Waiting until runtime to determine what kind and how many objects to create and use 1
36

12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Jul 15, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

12: Holding Your Objects

Waiting until runtime to determine what kind and how many objects to create and use

1

Page 2: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

2

A Collection is a group of individual elements.A List holds elements in a particular sequence with duplicates allowed.A Set has no implied order and duplicates are not allowed.A Queue holds elements in a particular order, usually FIFO.

Maps are groups of key-value object pairs. The objects may themselves be containers. A Map can produce:

a Set of its keys,a Collection of its values,a Set of its pairs.

Java Container Interfaces

Page 3: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Pre-Java SE5

3

import java.util.*;

class Apple { private static long counter; private final long id = counter++; public long id() { return id; }}

class Orange {}

public class ApplesAndOrangesWithoutGenerics { @SuppressWarnings("unchecked") public static void main(String[] args) { ArrayList apples = new ArrayList(); for(int i = 0; i < 3; i++) apples.add(new Apple()); // Not prevented from adding an Orange to apples: apples.add(new Orange()); for(int i = 0; i < apples.size(); i++) // Normally causes a compiler warning: ((Apple)apples.get(i)).id(); }}

Page 4: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

With Generics

4

public class ApplesAndOrangesWithGenerics { public static void main(String[] args) { ArrayList<Apple> apples = new ArrayList<Apple>(); for(int i = 0; i < 3; i++) apples.add(new Apple()); // Compile-time error: // apples.add(new Orange()); for(int i = 0; i < apples.size(); i++) System.out.println(apples.get(i).id()); // Using foreach: for(Apple c : apples) System.out.println(c.id()); }}

Page 5: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

The Collection Interface

5

import java.util.*;

public class SimpleCollection { public static void main(String[] args) { Collection<Integer> c = new ArrayList<Integer>(); for(int i = 0; i < 10; i++) c.add(i); // Autoboxing for(Integer i : c) System.out.print(i + ", "); }}

Page 6: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

6

public class AddingGroups { public static void main(String[] args) { Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5)); Integer[] moreInts = { 6, 7, 8, 9, 10 }; collection.addAll(Arrays.asList(moreInts)); // Runs significantly faster, but you can't // construct a Collection this way: Collections.addAll(collection, 11, 12, 13, 14, 15); Collections.addAll(collection, moreInts); // Produces a list "backed by" an array: List<Integer> list = Arrays.asList(16, 17, 18, 19, 20); list.set(1, 99); // OK -- modify an element // list.add(21); // Runtime error because the // underlying array cannot be resized. }}

Adding Groups to aCollection

Page 8: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

8

Java Collections

Final Class InterfaceKey

extends implements

java.util

Class Abstract Class

java.lang

Object

Arrays

Collections

AbstractCollection AbstractList AbstractSequential List LinkedList

ArrayList

HashSet

TreeSet

AbstractSet

AbstractQueuePriorityQueue

AbstractMap HashMap LinkedHashMap

Iteratable

Collection

List

Set

SortedSet

Queue

TreeMap

LinkedHashSet

List

Map SortedMap

Iterator

ListIterator

Set

Page 9: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

9

Unlike arrays, built-in functionality is provided.

The following example introduces basic container types.

Printing Containers

Page 10: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Printing Containers

10

public class PrintingContainers { static Collection fill(Collection<String> collection) { collection.add("rat"); collection.add("cat"); collection.add("dog"); collection.add("dog"); return collection; } static Map fill(Map<String,String> map) { map.put("rat", "Fuzzy"); map.put("cat", "Rags"); map.put("dog", "Bosco"); map.put("dog", "Spot"); return map; } public static void main(String[] args) { print(fill(new ArrayList<String>())); print(fill(new LinkedList<String>())); print(fill(new HashSet<String>())); print(fill(new TreeSet<String>())); print(fill(new LinkedHashSet<String>())); print(fill(new HashMap<String,String>())); print(fill(new TreeMap<String,String>())); print(fill(new LinkedHashMap<String,String>())); }}

[rat, cat, dog, dog][rat, cat, dog, dog][dog, cat, rat][cat, dog, rat][rat, cat, dog]{dog=Spot, cat=Rags, rat=Fuzzy}{cat=Rags, dog=Spot, rat=Fuzzy}{rat=Fuzzy, cat=Rags, dog=Spot}

Page 11: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

The List Interface

11

Lists hold their elements in a particular sequence.

Duplicates are allowed.

Insertion and removal operations are allowed from any position.

There are two implementations:

ArrayLists are backed by a resizable array.

LinkedLists stored as linked structures.

Page 13: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

13

It’s the default choice for a simple sequence.

Random access is optimized.

The ListIterator should be used only for bidirectional traversal of an ArrayList, but not for inserting and removing elements.

ArrayList

Page 14: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

14

The LinkedList class provides optimal sequential access with inexpensive insertions and deletions from the middle of the list.

It can be used as a stack, queue and deque by using the Queue interface.

LinkedList

Page 15: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

15

Iterators

Iterators abstract the process of selecting each element in a sequence, that is, to traverse a Collection.

Several iterators may be created allowing more than one element to be selected at a time.

The underlying collection is hidden so that types can easily be changed.

Page 18: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

A Stack Class

18

import java.util.LinkedList;

class Stack<T> { private LinkedList<T> storage = new LinkedList<T>(); public void push(T v) { storage.addFirst(v); } public T peek() { return storage.getFirst(); } public T pop() { return storage.removeFirst(); } public boolean empty() { return storage.isEmpty(); } public String toString() { return storage.toString(); }}

public class StackTest { public static void main(String[] args) { Stack<String> stack = new Stack<String>(); for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.empty()) System.out.print(stack.pop() + " "); }}

fleas has dog My

Page 21: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

21

Set Implementations

The HashSet implements the Set interface as a hash table and provides very fast lookups and insertions.

The TreeSet implements the SortedSet interface and allows the extraction of an ordered sequence.

The LinkedHashSet implements the Set interface, maintains insertion order and allows fast lookups and insertions.

Page 22: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

HashSet

22

public class SetOfInteger { public static void main(String[] args) { Random rand = new Random(47); Set<Integer> intset = new HashSet<Integer>(); for(int i = 0; i < 10000; i++) intset.add(rand.nextInt(30)); System.out.println(intset); }}

[15, 8, 23, 16, 7, 22, 9, 21, 6, 1, 29, 14, 24, 4, 19, 26, 11, 18, 3, 12, 27, 17, 2, 13, 28, 20, 25, 10, 5, 0]

Page 23: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

TreeSet

23

public class SortedSetOfInteger { public static void main(String[] args) { Random rand = new Random(47); SortedSet<Integer> intset = new TreeSet<Integer>(); for(int i = 0; i < 10000; i++) intset.add(rand.nextInt(30)); System.out.println(intset); }}

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Page 24: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

24

Maps

Maps are alternately called dictionaries or associative arrays.

They are used like arrays, but instead of using an integer index for lookup, another object is used as a key.

Items are stored as key/value pairs.

Duplicate keys are not allowed.

Keys are returned as Sets.

Values are returned as collections.

Page 27: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

27

Map Implementations

The HashMap implements the Map interface and is based on a hash table. It provides constant-time performance.

The LinkedHashMap is slightly slower than the HashMap and provides retrieval in insertion order.

The TreeMap implements the SortedMap interface, retrieves in key order and allows the extraction of sub maps.

The WeakHashMap and IdentityHashMap classes are also provided.

Page 28: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Map

28

public class Statistics { public static void main(String[] args) { Random rand = new Random(47); Map<Integer,Integer> m = new HashMap<Integer,Integer>(); for(int i = 0; i < 10000; i++) { // Produce a number between 0 and 20: int r = rand.nextInt(20); Integer freq = m.get(r); m.put(r, freq == null ? 1 : freq + 1); } System.out.println(m); }}

{15=497, 4=481, 19=464, 8=468, 11=531, 16=533, 18=478, 3=508, 7=471, 12=521, 17=509, 2=489, 13=506, 9=549, 6=519, 1=502, 14=477, 10=513, 5=503, 0=481}

Page 30: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Queue

30

public class QueueDemo { public static void printQ(Queue queue) { while(queue.peek() != null) System.out.print(queue.remove() + " "); System.out.println(); } public static void main(String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); Random rand = new Random(47); for(int i = 0; i < 10; i++) queue.offer(rand.nextInt(i + 10)); printQ(queue); Queue<Character> qc = new LinkedList<Character>(); for(char c : "Brontosaurus".toCharArray()) qc.offer(c); printQ(qc); }}

8 1 1 1 5 14 3 1 0 1B r o n t o s a u r u s

Page 31: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Priority Queue...

31

public class PriorityQueueDemo { public static void main(String[] args) { PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(); Random rand = new Random(47); for(int i = 0; i < 10; i++) priorityQueue.offer(rand.nextInt(i + 10)); QueueDemo.printQ(priorityQueue);

List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25); priorityQueue = new PriorityQueue<Integer>(ints); QueueDemo.printQ(priorityQueue); priorityQueue = new PriorityQueue<Integer>( ints.size(), Collections.reverseOrder()); priorityQueue.addAll(ints); QueueDemo.printQ(priorityQueue);

0 1 1 1 1 1 3 5 8 141 1 2 3 3 9 9 14 14 18 18 20 21 22 23 25 2525 25 23 22 21 20 18 18 14 14 9 9 3 3 2 1 1

Page 32: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

...Priority Queue

32

String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION"; List<String> strings = Arrays.asList(fact.split("")); PriorityQueue<String> stringPQ = new PriorityQueue<String>(strings); QueueDemo.printQ(stringPQ); stringPQ = new PriorityQueue<String>( strings.size(), Collections.reverseOrder()); stringPQ.addAll(strings); QueueDemo.printQ(stringPQ);

Set<Character> charSet = new HashSet<Character>(); for(char c : fact.toCharArray()) charSet.add(c); // Autoboxing PriorityQueue<Character> characterPQ = new PriorityQueue<Character>(charSet); QueueDemo.printQ(characterPQ); } }

A A B C C C D D E E E F H H I I L N N O O O O S S S T T U U U WW U U U T T S S S O O O O N N L I I H H F E E E D D C C C B A A A B C D E F H I L N O S T U W

Page 33: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Foreach and Collections

33

public class ForEachCollections { public static void main(String[] args) { Collection<String> cs = new LinkedList<String>(); Collections.addAll(cs, "Take the long way home".split(" ")); for(String s : cs) System.out.print("'" + s + "' "); }}

'Take' 'the' 'long' 'way' 'home'

Page 34: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Foreach and Iterators

34

public class IterableClass implements Iterable<String> { protected String[] words = ("And that is how " + "we know the Earth to be banana-shaped.").split(" "); public Iterator<String> iterator() { return new Iterator<String>() { private int index = 0; public boolean hasNext() { return index < words.length; } public String next() { return words[index++]; } public void remove() { // Not implemented throw new UnsupportedOperationException(); } }; } public static void main(String[] args) { for(String s : new IterableClass()) System.out.print(s + " "); } }

And that is how we know the Earth to be banana-shaped.

Page 35: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

Summary

35

Prefer interfaces to implementations:

A Collection holds single elements.

A Map holds associated pairs.

A List is an ordered container.

A Set is a collection of unique elements.

A Queue can also serve as a stack.

An Iterator can be produced from any Collection.

Page 36: 12: Holding Your Objects - Sonicgaryb/Courses/Java/Slides/Ch12.pdf · 2008-03-12 · Key Final Class Interface extends implements java.util Class Abstract Class java.lang Object Arrays

36

Java Collections

Final Class InterfaceKey

extends implements

java.util

Class Abstract Class

java.lang

Object

Arrays

Collections

AbstractCollection AbstractList AbstractSequential List LinkedList

ArrayList

HashSet

TreeSet

AbstractSet

AbstractQueuePriorityQueue

AbstractMap HashMap LinkedHashMap

Iteratable

Collection

List

Set

SortedSet

Queue

TreeMap

LinkedHashSet

List

Map SortedMap

Iterator

ListIterator

Set