By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

23
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua Block

description

Java's Collection Framework. By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block. Overview. - PowerPoint PPT Presentation

Transcript of By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

Page 1: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

1

Java's Collection Framework

By Rick Mercer with help from

The Java Tutorial, The Collections Trail, by Joshua Block

Page 2: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

2

Overview

Framework (in software): a general system of components and architectural solutions that provides development tools to programmers for use with a relatively wide range of applications.

Collection: (hmm...) any collection of elements

Page 3: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

3

Collection Framework

A collections framework is a unified architecture for representing and manipulating collections. It has: – Interfaces: abstract data types representing collections

– Implementations: concrete implementations of the collection interfaces

– Algorithms: methods that perform useful computations, such as searching and sorting• These algorithms are said to be polymorphic: the same method

can be used on different implementations

Page 4: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

4

Interfaces

An interface describes a set of methods: – no constructors or instance variables

Interfaces must be implemented by classes– 646 java classes implement >= 1 interfaces (‘02)

2 or more classes implement an interface– Classes guaranteed to have the same methods– Objects can be treated as the same type– Can use different algorithms / instance variables

Page 5: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

5

Collection interfaces

Queuesince Java 5

Click here for a Annotated Outline of Collections Framework

Page 6: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

6

Implementations

A collection class– implements an ADT as a Java class– implements all methods of the interface– selects appropriate instance variables– can be instantiated

Java implements interfaces with– List: ArrayList, LinkedList, Vector– Map: HashMap, TreeMap– Set: TreeSet, HashSet

Page 7: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

7

Algorithms

Java has polymorphic algorithms to provide functionality for different types of collections– 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 8: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

8

Two Useful ADTs

List: a collection with a first element, a last element, distinct predecessors and successors– duplicates that "equals" each other are allowed

Map: maps keys to values – Maps cannot contain duplicate keys

– Each key maps at most one value

Page 9: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

9

List

A list is– a collection of elements (numbers, strings,

accounts, pictures,…) – ordered (a sequence): there is a first, and a last

element• lists can be empty – no elements

– elements with a unique predecessor and successor– also known as a sequence

Peruse the Java 5 List Interface

Page 10: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

10

ArrayList A Java Collection Class that Implements List

ArrayList – stores a collection of any type of object

– can be all the same type, or different types

– similar functionality to an array, but does not use subscripts

– is an indexed collection

The next slide is part of Sun's documentation

Page 11: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

11

ArrayList Java

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Page 12: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

12

List implemented by 3 classes

// 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 methodbigList.add("in array list");littleList.add("in linked list");sharedList.add("in vector"); // All three have a get methodassertEquals("in array list", bigList.get(0));assertEquals("in linked list", littleList.get(0));assertEquals("in vector", sharedList.get(0));

Page 13: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

13

Java 5 Generics

A List can be made to store only one type

List<BankAccount> accountList = new ArrayList <BankAccount>();

accountList.add(new BankAccount("One", 111.11)); accountList.add(new BankAccount("Two", 222.22)); accountList.add(new BankAccount("Three", 333.33)); accountList.add(new BankAccount("Four", 444.44)); System.out.println(accountList.toString());

Output

[One $111.11, Two $222.22, Three $333.33, Four $444.44]

Page 14: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

14

Iterators

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 15: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

15

Map and SortedMap

The Map interface defines methods – get, put, contains, keySet, values, entrySet

TreeMap implements Map– put, get, remove: O(log n)

HashMap implements Map– put, get, remove: O(1)

Page 16: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

16

Set and SortedSet

Some Map methods return SetThe Set interface

– add, addAll, remove, size, but no get!

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

Page 17: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

17

Let's play

Set up a small collection of mappings Map<String, BankAccount> tm = new TreeMap<String, BankAccount>();

tm.put("M", new BankAccount("Michel", 111.11)); tm.put("G", new BankAccount("Georgie", 222.22)); tm.put("S", new BankAccount("Sam", 333.33)); tm.put("P", new BankAccount("Pei", 444.44)); tm.put("Z", new BankAccount("Zac", 555.55));

// Coming up: Some Map methods

Page 18: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

18

keySet()

// Get the set of keys in the Map. // With TreeMap, the keys are ordered. Set<String> keys = tm.keySet(); assertEquals("[G, M, P, S, Z]", keys.toString());

Page 19: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

19

values()

// The valuesCollection<BankAccount> accountCollection = tm.values();

Iterator<BankAccount> itr = accountCollection.iterator();

double allTheMoney = 0.0;while (itr.hasNext()) { allTheMoney += itr.next().getBalance();}assertEquals(1666.65, allTheMoney, 0.01);

Page 20: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

20

entrySet()

// The mappingsCollection<Entry<String, BankAccount>> mapping = tm.entrySet();

Iterator<Entry<String, BankAccount>> itr2 = mapping.iterator();

while (itr2.hasNext()) { System.out.print("<" +itr2.next().toString() + "> ");}

<G=Georgie $222.22> <M=Michel $111.11> <P=Pei $444.44> <S=Sam $333.33> <Z=Zac $555.55>

Page 21: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

21

Enhanced for Loop

for can iterate over collections for (Type element : collection) { element is the next thing visited for each iteration }ArrayList<String> names = new ArrayList<String>();names.add("Aaron");names.add("Moksha");names.add("Drew");names.add("Qiyam");for (String name : names) System.out.print(name + " "); Output Aaron Moksha Drew Qiyam

Page 22: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

22

Use for over iterator

Collection<BankAccount> accountCollection = tm.values();double allTheMoney = 0.0;

for (BankAccount nextAccount : accountCollection) allTheMoney += nextAccount.getBalance();

assertEquals(1666.65, allTheMoney, 0.01);

Page 23: By Rick Mercer with help from The Java Tutorial, The Collections Trail , by Joshua Block

23

Algorithms

See the Java API for the Collections class– play with sort, binarySearch, reverse, shuffle

• your choice