0% found this document useful (0 votes)
26 views24 pages

3 Collections

java collection

Uploaded by

abhijitddas19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views24 pages

3 Collections

java collection

Uploaded by

abhijitddas19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 24

Exploring the Java

Collections Framework

SOFTENG 251
Object Oriented Software Construction
Preamble
Tutorial?
Review of Generics
More on Collections Lists, Sets, Maps, algorithms
Assignment queries
Go over exercise(s) from Wiki
Friday session group 8
Multi-choice questions, and/or
Mini-exercise
Polymorphism, generics, collections

Collections framework SOFTENG 251 Object Oriented Software Construction 2


Recap
List<E> is a generic type (furthermore its a generic interface)
ArrayList<E> is a generic class, which implements List<E>
E is a type variable/ List<Money> list = new ArrayList<Money>();
type parameter

public class ArrayList<E> List/ArrayList both


implements List<E> { parameterised with Money
private E[] elementData;
public class ArrayList
private int size;
implements List<Money> {
... //stuff
private Money[] elementData;
public boolean add(E o) { private int size;
elementData[size++] = o; ... //stuff
return true; public boolean add(Money o) {
} elementData[size++] = o;
public E get(int i) { return true;
return elementData[i]; }
} //etc... public Money get(int i) {
When you parameterise ArrayList<E> return elementData[i];
}
with Money, think of it as: } //etc...
E becomes Money }
Collections framework SOFTENG 251 Object Oriented Software Construction 3
More than just Lists
ArrayLists and LinkedLists are just two of the many classes
comprising the Java Collections Framework (JCF)
A collection is an object that maintains references to others objects
Essentially a subset of data structures
JCF forms part of the java.util package and provides:
Interfaces
Each defines the operations and contracts for a particular type of collection
(List, Set, Queue, etc)
Idea: when using a collection object, its sufficient to know its interface
Implementations
Reusable classes that implement above interfaces (e.g. LinkedList, HashSet)
Algorithms
Useful polymorphic methods for manipulating and creating objects whose
classes implement collection interfaces
Sorting, index searching, reversing, replacing etc.

Collections framework SOFTENG 251 Object Oriented Software Construction 4


Generalisation
Interfaces
A special Root interface for operations Stores mappings from
Collection that common to all types of collections keys to values
cannot contain
duplicates. Collection Map

Set List Queue SortedMap

Specialises collection with Special map in


operations for FIFO and priority which keys are
SortedSet queues. ordered
Stores a sequence of elements,
allowing indexing methods
Special Set that retains
ordering of elements. Specialisation
Collections framework SOFTENG 251 Object Oriented Software Construction 5
Expansion of contracts
<<interface>>
List<E>
+add(E):boolean
+remove(Object):boolean
+get(int):E
+indexOf(Object):int
<<interface>> +contains(Object):boolean
+size():int
Collection<E>
+iterator():Iterator<E>
+add(E):boolean etc
+remove(Object):boolean
<<interface>>
+contains(Object):boolean
+size():int SortedSet<E>
+iterator():Iterator<E> <<interface>>
+add(E):boolean
etc Set<E> +remove(Object):boolean
+add(E):boolean +contains(Object):boolean
+remove(Object):boolean +size():int
+contains(Object):boolean +iterator():Iterator<E>
+size():int +first():E
+iterator():Iterator<E> +last():E
etc etc

Collections framework SOFTENG 251 Object Oriented Software Construction 6


java.util.Iterator<E>
Think about typical usage scenarios for Collections
Retrieve the list of all patients
Search for the lowest priced item
More often than not you would have to traverse every element in
the collection be it a List, Set, or your own datastructure
Iterators provide a generic way to traverse through a collection
regardless of its implementation
a Set
iterator() c
next():d f
g
d h
a b c d e f g h i b e
i
hasNext()?
List
Iterator
iterator() a b c d e f g h i

Collections framework SOFTENG 251 Object Oriented Software Construction 7


Using an Iterator
Quintessential code snippet for collection iteration:
public void list(Collection<Item> items) {
Iterator<Item> it = items.iterator(); <<interface>>
while(it.hasNext()) { Iterator<E>
Item item = it.next(); +hasNext():boolean
System.out.println(item.getTitle()); +next():E
} +remove():void
}

Design notes:
Above method takes in an object whose class implements Collection
List, ArrayList, LinkedList, Set, HashSet, TreeSet, Queue, MyOwnCollection, etc
We know any such object can return an Iterator through method iterator()
We dont know the exact implementation of Iterator we are getting, but we
dont care, as long as it provides the methods next() and hasNext()
Good practice: Program to an interface!

Collections framework SOFTENG 251 Object Oriented Software Construction 8


java.lang.Iterable<T>
Iterator<Item> it = items.iterator();
for (Item item : items) { while(it.hasNext()) {

}
System.out.println(item); = Item item = it.next();
System.out.println(item);
}

This is called a for-each statement <<interface>>


For each item in items Iterable<T>
This is possible as long as items is of type Iterable +iterator():Iterator<T>
Defines single method iterator()
Collection (and hence all its subinterfaces)
implements Iterable
Collection<T> MyBag<T>
You can do this to your own implementation of
Iterable too!
To do this you may need to return your own
etc
implementation of Iterator Set<T> List<T>

Collections framework SOFTENG 251 Object Oriented Software Construction 9


java.util.Collections
Offers many very useful utilities and algorithms for manipulating
and creating collections
Sorting lists
Index searching
Finding min/max
Reversing elements of a list
Swapping elements of a list
Replacing elements in a list
Other nifty tricks
Saves you having to implement
them yourself reuse

Collections framework SOFTENG 251 Object Oriented Software Construction 10


Collections.sort()
Javas implementation of merge sort ascending order

e b c d b f a a b b c d e f
0 1 2 3 4 5 6 0 1 2 3 4 5 6

What types of objects can you sort? Anything that has an ordering
Two sort() methods: sort a given List according to either 1) natural
ordering of elements or an 2) externally defined ordering.
1) public static <T extends Comparable<? super T>> void sort(List<T> list)

2) public static <T> void sort(List<T> list, Comparator<? super T> c)

Translation:
1. Only accepts a List parameterised with type implementing Comparable
2. Accepts a List parameterised with any type as long as you also give it a
Comparator implementation that defines the ordering for that type
Collections framework SOFTENG 251 Object Oriented Software Construction 11
java.lang.Comparable<T>
A generic interface with a single method: int compareTo(T)
Return 0 if this = other
Return any +ve integer if this > other
Return any ve integer if this < other
Implement this interface to define natural ordering on objects of type T
public class Money implements Comparable<Money> {
...
public int compareTo( Money other ) { m1 = new Money(100,0);
if( this.cents == other.cents ) { m2 = new Money(50,0);
return 0; m1.compareTo(m2) returns 1;
}
else if( this.cents < other.cents ) {
return -1;
}
else { A more concise way of doing this? (hint: 1 line)
return 1;
} return this.cents other.cents;
}

Collections framework SOFTENG 251 Object Oriented Software Construction 12


Natural-order sorting
List<Money> funds = new ArrayList<Money>();
funds.add(new Money(100,0));
funds.add(new Money(5,50)); Whats the output?
funds.add(new Money(-40,0)); [-40.0,
funds.add(new Money(5,50)); 5.50,
funds.add(new Money(30,0)); 5.50,
30.0,
Collections.sort(funds); 100.0]
System.out.println(funds);

List<CD> albums = new ArrayList<CD>();


albums.add(new CD("Street Signs","Ozomatli",2.80));
//etc...
Collections.sort(albums);
CD does not implement a
Comparable interface

public static <T extends Comparable<? super T>> void sort(List<T> list)

Wildcard (later)
Collections framework SOFTENG 251 Object Oriented Software Construction 13
java.util.Comparator<T>
Useful if the type of elements to be sorted is not Comparable, or
you want to define an alternative ordering <<interface>>
Also a generic interface that defines methods Comparator<T>
compare(T,T) and equals(Object) +compare(T o1, T o2):int
+equals(Object other):boolean
Usually only need to define compare(T,T)
Define ordering by CDs getPrice() Money CD
Note: PriceComparator implements a Comparator para- +getTitle():String
meterised with CD T becomes CD +getArtist():String
+getPrice():Money
public class PriceComparator
implements Comparator<CD> {
public int compare(CD c1, CD c2) {
return c1.getPrice().compareTo(c2.getPrice());
}
}
Comparator and Comparable
going hand in hand

Collections framework SOFTENG 251 Object Oriented Software Construction 14


Comparator sorting
List<CD> albums = new ArrayList<CD>();
albums.add(new CD("Street Signs","Ozomatli",new Money(3,50)));
albums.add(new CD("Jazzinho","Jazzinho",new Money(2,80)));
albums.add(new CD("Space Cowboy","Jamiroquai",new Money(5,00)));
albums.add(new CD("Maiden Voyage","Herbie Hancock",new Money(4,00)));
albums.add(new CD("Here's the Deal","Liquid Soul",new Money(1,00)));

Collections.sort(albums, new PriceComparator());


System.out.println(albums);
implements Comparator<CD>

Note, in sort(), Comparator overrides natural ordering


i.e. Even if we define natural ordering for CD, the given comparator is
still going to be used instead
(On the other hand, if you give null as Comparator, then natural
ordering is used)

public static <T> void sort(List<T> list, Comparator<? super T> c)

Collections framework SOFTENG 251 Object Oriented Software Construction 15


Set<E>
Mathematical Set abstraction contains no duplicate elements
i.e. no two elements e1 and e2 such that e1.equals(e2)
<<interface>>
Set<E>
add(x) remove(c) +add(E):boolean
true a b b +remove(Object):boolean
true c +contains(Object):boolean
c x +isEmpty():boolean
add(b) remove(x) d
d a +size():int
false false +iterator():Iterator<E>
etc

contains(e) ? isEmpty()
true a b false <<interface>>
e SortedSet<E>
contains(x) c size() +first():E
false d
5 +last():E
etc

Collections framework SOFTENG 251 Object Oriented Software Construction 16


HashSet<E>
<<interface>>
Set<E>
Typically used implementation of Set. +add(E):boolean
Hash? Implemented using HashMap (later) +remove(Object):boolean
+contains(Object):boolean
Parameterise Sets just as you parameterise Lists +size():int
+iterator():Iterator<E>
Efficient (constant time) insert, removal and etc
contains check all done through hashing
x and y are duplicates if x.equals(y)
How are elements ordered? Quiz: HashSet<E>
Set<String> words = new HashSet<String>();
words.add("Bats");
words.add("Ants");
3 a) Bats, Ants, Crabs
words.add("Crabs");
words.add("Ants"); b) Ants, Bats, Crabs
System.out.println(words.size()); c) Crabs, Bats, Ants
for (String word : words) {
d) Nondeterministic
}
System.out.println(word); ?
Collections framework SOFTENG 251 Object Oriented Software Construction 17
TreeSet<E> (SortedSet<E>)
If you want an ordered set, use an implementation <<interface>>
SortedSet<E>
of a SortedSet: TreeSet +first():E
Whats up with Tree? Red-black tree +last():E
etc
Guarantees that all elements are ordered (sorted)
at all times
add() and remove() preserve this condition TreeSet<E>
iterator() always returns the elements in a
specified order
Two ways of specifying ordering
Ensuring elements have natural ordering (Comparable)
Giving a Comparator<E> to the constructor
Caution: TreeSet considers x and y are duplicates if
x.compareTo(y) == 0 (or compare(x,y) == 0)

Collections framework SOFTENG 251 Object Oriented Software Construction 18


TreeSet construction
Set<String> words = new TreeSet<String>(); String has a natural
words.add("Bats"); ordering, so empty
words.add("Ants"); constructor
words.add("Crabs");
for (String word : words) { Whats the output?
System.out.println(word); Ants; Bats; Crabs
}

But CD doesnt, so you must pass in a Comparator to the constructor

Set<CD> albums = new TreeSet<CD>(new PriceComparator());


albums.add(new CD("Street Signs","O",new Money(3,50)));
albums.add(new CD("Jazzinho","J",new Money(2,80)));
albums.add(new CD("Space Cowboy","J",new Money(5,00)));
albums.add(new CD("Maiden Voyage","HH",new Money(4,00)));
albums.add(new CD("Heres the Deal","LS",new Money(2,80)));
System.out.println(albums.size());
for (CD album : albums) { Whats the output?
System.out.println(album); 4
} Jazzinho; Street; Maiden; Space

Collections framework SOFTENG 251 Object Oriented Software Construction 19


Map<K,V>
Stores mappings from (unique) keys (type K) to values (type V)
See, you can have more than one type parameters!
Think of them as arrays but with objects (keys) as indexes
Or as directories: e.g. "Bob" 021999887
<<interface>>
get(k) put(x,e) put(k,f) Map<K,V>
a k a null a
a +put(K,V):V
m b k a +get(Object):V
get(x) m b k f +remove(Object):V
null p c
p c m b +size():int
n b +keySet():Set<K>
size() n b p c +values():Collection<V>
keys values
4 x e n b etc

remove(n) values()
k a keySet() Collection
b <<interface>>
m b Set SortedMap<K,V>
k a
remove(x) p c b
m p +firstKey():K
null c b +lastKey():K
n b n etc
Collections framework SOFTENG 251 Object Oriented Software Construction 20
HashMap<K,V>
<<interface>>
aka Hashtable (SE250) Map<K,V>
keys are hashed using Object.hashCode() +put(K,V):V
+get(Object):V
i.e. no guaranteed ordering of keys +remove(Object):V
keySet() returns a HashSet +size():int
+keySet():Set<K>
values() returns an unknown Collection +values():Collection<V>
etc
Map<String, Integer> directory
= new HashMap<String, Integer>();
directory.put("Mum", new Integer(9998888));
directory.put("Dad", 9998888); HashMap<K,V>
directory.put("Bob", 12345678); autoboxing
directory.put("Edward", 5553535);
directory.put("Bob", 1000000);
4 or 5?
System.out.println(directory.size());
for (String key : directory.keySet()) {
System.out.print(key+"'s number: "); Set<String>
System.out.println(directory.get(key));
} Whats Bobs number?
System.out.println(directory.values());

Collections framework SOFTENG 251 Object Oriented Software Construction 21


TreeMap<K,V>
Guaranteed ordering of keys (like TreeSet)
In fact, TreeSet is implemented using TreeMap <<interface>>
SortedMap<K,V>
Hence keySet() returns a TreeSet
+firstKey():K
values() returns an unknown Collection ordering +lastKey():K
depends on ordering of keys etc
Empty constructor
natural ordering
Map<String, Integer> directory
= new TreeMap<String, Integer>(); TreeMap<K,V>
directory.put("Mum", new Integer(9998888));
directory.put("Dad", 9998888);
directory.put("Bob", 12345678);
directory.put("Edward", 5553535); 4 Loop output?
directory.put("Bob", 1000000); Bob's #: 1000000
System.out.println(directory.size()); Dad's #: 9998888
for (String key : directory.keySet()) { Edward's #: 5553535
System.out.print(key+"'s #: "); Mum's #: 9998888
System.out.println(directory.get(key));
}
System.out.println(directory.values()); ?
Collections framework SOFTENG 251 Object Oriented Software Construction 22
TreeMap with Comparator
As with TreeSet, another way of constructing TreeMap is to give a
Comparator necessary for non-Comparable keys

Map<CD, Double> ratings


= new TreeMap<CD, Double>(new PriceComparator());
ratings.put(new CD("Street Signs","O",new Money(3,50)), 8.5);
ratings.put(new CD("Jazzinho","J",new Money(2,80)), 8.0);
ratings.put(new CD("Space Cowboy","J",new Money(5,00)), 9.0);
ratings.put(new CD("Maiden Voyage","H",new Money(4,00)), 9.5);
ratings.put(new CD("Here's the Deal","LS",new Money(2,80)), 9.0);
4
System.out.println(ratings.size());
Ordered by keys
for (CD key : ratings.keySet()) {
price
System.out.print("Rating for "+key+": ");
System.out.println(ratings.get(key));
} Depends on
System.out.println("Ratings: "+ratings.values()); key ordering

Collections framework SOFTENG 251 Object Oriented Software Construction 23


But wait, theres more!
Now you know the main interfaces and implementations from the
Collections framework, look them up on the Java API documentation to find
out in more detail on how to use them

interface interface
Collection Map

interface
interface interface interface
Set List Queue SortedMap

HashSet interface Vector ArrayList LinkedList TreeMap HashMap


SortedSet

Linked TreeSet
HashSet Implementations

Collections framework SOFTENG 251 Object Oriented Software Construction 24

You might also like