Title: Collections
1Collections
2Collection
- A Collection is a group or set of objects. Also
called a container. - Set
- an unordered collection
- no duplicates.
- List
- ordered collection, duplicates are allowed
- can insert/delete elements anywhere
- Queue and Stack
- special rules for LIFO, FIFO disciplines
3Collections in Programming
- Collections are essential to many applications.
- Example read some words from the console and
save in a list. We don't know how many words.
ListltStringgt wordlist new ArrayListltStringgt( )
while ( console.hasNext( ) ) String word
console.next( ) wordlist.add( word ) // how
many words are there? int number wordlist.size(
) // sort the words Collections.sort( wordlist
) // does it contain the word "dog" if (
wordlist.contains( "dog" ) ) ...
4Java Collections
Collection a group of objects
Map mapping of a set to another
Set unordered, no duplicates
List ordered, duplicates ok
Queue FIFO discipline
HashMap map using a hash table
Sorted Set Set with total ordering
ArrayList
Priority Queue
LinkedList
ArrayDeque
HashSet
5What can a Collection do?
Collection a group of objects
add( Element ) clear( ) contains( Element
) isEmpty( ) iterator( ) remove( Element ) size(
) toArray( )
creates
Iterator hasNext( ) bool next( )
Element remove( )
6What can a Set do?
Collection a group of objects
add( Element ) clear( ) contains( Element
) isEmpty( ) iterator( ) remove( Element ) size(
) toArray( )
Set unordered, no duplicates
Sorted Set Set with total ordering
A set provides the same behavior as a Collection,
but with some extra guarantees, such as "no
duplicates".
HashSet
7Set Example
Get students in my class, and kick out any hacker.
// The getClass( ) method returns students as a
Set SetltStudentgt myclass Registrar.getClass(
"214531" ) // Is the student "hacker" in the
set? if ( myclass.contains( hacker ) )
myclass.remove( hacker )
8What can a List do?
Collection a group of objects
add( Element ) clear( ) contains( Element
) isEmpty( ) iterator( ) remove( Element ) size(
) toArray( )
List ordered, duplicates ok
ArrayList
add( index, Element ) get( index ) indexOf(
Element ) remove( index )
LinkedList
A list adds ability to access any element by its
position
9List Example
// getClassList returns a List of
students ListltStudentgt myclass new
ArrayListltStudentgt( ) myclass
Registrar.getClassList( "214531" ) // sort the
students Collections.sort( myclass ) // print
all the students in the class for ( Student st
myclass ) System.out.println( st.toString()
)
A "for-each" loop words with any collection
10What can a Map do?
Map keys to values key ? value
Map mapping of a set to another
HashMap map using a hash table
clear( ) get( Key ) Value keySet( ) get a Set
of all keys put( Key, Value ) remove( Key ) size(
) values( ) a Collection of values
11Map Example
Create a map between Coupon colors and money
values.
MapltString,Integergt map new HashMapltString,Integ
ergt( ) map.put( "red", 100 ) // red is worth
100 Baht map.put( "blue", 50 ) // blue is worth
50 Baht map.put( "green", 10 ) int x map.get(
"blue") /// returns x 50 // now process a
coupon String color console.next( ) // get
the coupon's color if ( map.containsKey( color )
) value map.get( color ) total total
value
12The Java Collections Framework
ltltinterfacegtgt Collection
ltltinterfacegtgt Map
extends
ltltinterfacegtgt Set
ltltinterfacegtgt List
ltltinterfacegtgt Queue
HashMap map using a hash table
implements
Sorted Set Set with total ordering
ArrayList
Priority Queue
LinkedList
ArrayDeque
HashSet
13Collections all use a Type parameter
- This is for safer and easier programming.
- You don't need to use "cast" to convert to data
type. - Student student (Student)list.get(k)
No
ListltStudentgt myclass new ArrayListltStudentgt(
) Student who myclass.get( 0 )
myclass can only contain elements of type
"Student". myclass.get( k ) always returns a
Student object.
14All Collections are Iterable
ltltinterfacegtgt Iterable iterator() Iterator
This means you can use a "foreach" loop to
transverse the elements of any collection. ListltSt
udentgt myclass myclass regis.getClass(
) for(Student s myclass ) ...
ltltinterfacegtgt Collection
ltltinterfacegtgt Set
ltltinterfacegtgt List
ltltinterfacegtgt Queue
15How to Iterate over a Collection (1)
Collection collection ... Iterator it
collection.iterator( ) while ( it.hasNext( ) )
Object obj it.next( ) // do something
16A "for each" loop
- for-each x in myAddressbook
- call x and invite him to party
- end
17How to Iterate over a Collection (2)
Java "for - each" loop for( Type x Iterable )
... for( Type x array ) ...
ListltCoingt coins new ArrayListltCoingt( ) for(
Coin x coins ) x.getValue( )
18Parts of the Collections Framework
- Interfaces - define behavior of the collection
types - Implementations - the concrete collection classes
- Polymorphic Algorithms - the same operation is
implemented by many different types of
collection. - and
- the algorithms apply to any data type in the
collection.
19Example of Polymorphism
any implementation is OK
CollectionltStudentgt coll new LinkedListltStudentgt
( ) coll .add( new Student( id1, name1) ) coll
.add( new Student( id2, name3) ) int n coll
.size( ) Collections.sort( coll ) for( Student
student coll ) System.out.println( student
)
20Example of Polymorphism (2)
CollectionltBirdgt coll new LinkedListltBirdgt( )
coll .add( new Bird( id1, name1) ) coll .add(
new Bird( id2, name3) ) int n coll .size(
) Collections.sort( coll ) for( Object student
coll ) System.out.println( student )
21Array Operations
- All Collections have a toArray( ) method.
- This lets you convert any collection to an array.
CollectionltStudentgt myclass Registrar.getClass(
"214531" ) // create an array to hold the
students Student array new Student
myclass.size( ) // copy the List to
array myclass.toArray( array )
22Exercise
- For the KU Coupons application, write a Store
class that records all the Transactions in an
ArrayList. - Write a getTotalSales( ) method that sums the
sales amount in all Transactions. - Write a printSalesReport( ) to print the sales.
23Resource
- "Collections Trail" in the Java Tutorial
- http//java.sun.com/docs/books/tutorial/index.htm
l