Title: Collections Lists and Sets
1CollectionsLists and Sets
2Collection hierarchyfrom java.util
Collection ltltinterfacegtgt
List ltltinterfacegtgt
Set ltltinterfacegtgt
3List hierarchy
List ltltinterfacegtgt
ArrayList
LinkedList
4ArrayList
- methods
- int size()
- boolean add(Object obj)
- adjusts size (and capacity as necessary)
- Object get(int index)
- Object set(int index, Object obj)
- replaces element at index with obj, returns old
element - void add(int index, Object obj)
- inserts obj at index , slides all elements from
index and higher up one position in the array,
adjusting size (and capacity as necessary) - Object remove(int index)
- removes and returns object at index, sliding all
elements from the position index1 and above one
position down the array, adjusts size
5ArrayList
- Complexity based on array implementation
- O(1)
- add(Object obj) amortized
- get(int index)
- set(int index, Object obj)
- O(size - index)
- add(int index, Object obj)
- remove(int index)
6interface List
- Methods
- int size()
- boolean add(Object obj)
- adjusts size
- Object get(int index)
- Object set(int index, Object obj)
- replaces element at index with obj, returns old
element - Iterator iterator()
- ListIterator listIterator()
- Note ArrayList implements all of these
7LinkedList
- implements List methods
- additional methods
- void addFirst(Object obj)
- void addLast(Object obj)
- Object getFirst()
- Object getLast()
- Object removeFirst()
- Object removeLast()
- Complexity based on doubly linked list
- additional methods are O(1)
- List methods using index are O(N)
8Accessing lists, interface Iterator
- From the iterator design pattern
- use the same methods for accessing elements,
regardless of underlying implementation - specified by the interface List (in fact, by
Collection) - methods
- boolean hasNext()
- Object next() -- returns next item and advances
- void remove() -- removes last item returned by
next
9Iterator code
- ArrayList list
- ...
- for(int k 0 k lt list.size() k)
- Object item list.get(k) // cast if necessary
- // do something with item
-
- List list
- ... // may be an ArrayList or a LinkedList
- Iterator itr list.iterator()
- while(itr.hasNext())
- Object item itr.next() // cast if necessary
- // do something with item
-
10Lists and arrays
- Use an array if
- known and fixed size
- access by index used (access, set)
- insertion, deletion from middle not used or rare
- Use an ArrayList if
- unknown or changing size
- appending at end is common
- access by index used (access, set)
- insertion, deletion from middle not used or rare
11Lists and arrays
- Use a LinkedList if
- Access by index not used or rare
- Additions and removals at either end
- iteration through list to access in order and
possibly remove - Note a List can be specified as a type of
variable or parameter, then an ArrayList or
LinkedList is actually used. - scope of declaration can only use List methods
12Examples
- Arrays
- arrays of elevators, elevator control panels,
buttons - for loops to create
- loop to find minimum
13Examples
- MBS list of neighbors returned by environment is
an ArrayList - MBS Fish creates a list of empty neighbors as an
ArrayList - These could be List just as well
- loops would use iterators
- actual objects could be ArrayList or LinkedList
14MBS Fish
- protected ArrayListltLocationgt emptyNeighbors()
-
- ArrayListltLocationgt nbrs
- environment().neighborsOf(location())
- ArrayListltLocationgt emptyNbrs
- new
ArrayListltLocationgt() - for ( int index 0 index lt nbrs.size()
index ) -
- Location loc nbrs.get(index)
- if ( environment().isEmpty(loc) )
- emptyNbrs.add(loc)
-
- return emptyNbrs
15MBS Fish, LinkedList version
- protected ListltLocationgt emptyNeighbors()
-
- ListltLocationgt nbrs
- environment().neighborsOf(locatio
n()) - ListltLocationgt emptyNbrs new
LinkedListltLocationgt() - Iterator,Locationgt itr nbrs.iterator()
- while( itr.hasNext())
-
- Location loc itr.next()
- if ( environment().isEmpty(loc) )
- emptyNbrs.add(loc)
-
- return emptyNbrs
-
- // Note method that calls this method
(nextLocation) will - // now need to use an iterator, cannot
assume - // return type other than List
16MBS Fish, for each loop
- protected ListltLocationgt emptyNeighbors()
-
- ListltLocationgt nbrs
- environment().neighborsOf(locatio
n()) - ListltLocationgt emptyNbrs new
LinkedListltLocationgt() - for(Location loc nbrs)
-
- if ( environment().isEmpty(loc) )
- emptyNbrs.add(loc)
-
- return emptyNbrs
17Set hierarchy
Set ltltinterfacegtgt
SortedSet ltltinterfacegtgt
HashSet
TreeSet
18interface Set
- Sets do not contain duplicates, according to
equals - methods
- int size()
- boolean add(Object obj) if not already there
- boolean remove(Object obj) if there
- boolean contains(Object obj)
- according to equals match
- Iterator iterator()
- Implemented by HashSet and TreeSet (sorted)
- no additional methods for either
19TreeSet
- Implementation is a balanced binary search tree
- requires elements that implement Comparable
- should be consistent with equals method for items
- only zero-parameter constructor is in AP subset
- Actually implements SortedSet (not part of AP)
- student are responsible to know iterator returns
items in order - Complexity - based on BBST (N size)
- O(log N) for given operations
- Iterator runs over all elements in O(N) time
20interface Comparable
- method
- int compareTo(Object other)
- returns value lt zero if this is less than rhs
- returns zero if this equals rhs
- returns value gt zero if this is greater than rhs
- should throw exception if rhs is not appropriate
type - usually thrown by downcast within method code
21Example MBS Location
public int compareTo(Object other) Location
otherLoc (Location) other if (
equals(other) ) return 0 if ( row()
otherLoc.row() ) return col() -
otherLoc.col() return row() -
otherLoc.row()
22HashSet
- Implementation is a hash table
- requires elements that implement hashCode
- should be consistent with equals method for items
- only zero-parameter constructor is in AP subset
- Does not implement SortedSet
- no particular order to iterator
- Complexity - based on hash table
- O(1) for given operations
- Iterator runs over all elements in O(size) time
- technically O(sizecapacity) but capacity is
normally proportional to size
23method hashCode
- part of every class, inherited from Object
- must be overridden appropriately for a class
- override should be consistent with equals
- recommend that equals and hashCode always be
implemented together (not for A course) - properties
- fast
- equals instances return same value
- return values evenly (randomly) distributed over
range of integers
24Example MBS Location
public int hashCode() return row() 3737
col() // alternate that works for many
classes // as long as toString is the same for //
equal objects and different for unequal public
int hashCode() return toString().hashCode()
25MBS Fish, Set version
- // precondition Env method neighborsOf returns a
Set - protected SetltLocationgt emptyNeighbors()
-
- SetltLocationgt nbrs
- environment().neighborsOf(location
()) - SetltLocationgt emptyNbrs new
HashSetltLocationgt() - // or
TreeSetltLocationgt() -
- for(Location loc nbrs)
-
- if ( environment().isEmpty(loc) )
- emptyNbrs.add(loc)
-
- return emptyNbrs
-
- // could also use iterator exactly as with lists
26Applications of Set
- In Maze program, the maze class could store a Set
of Locations that are walls - isWall method calls contains for the Set
- could use TreeSet or HashSet
- compareTo and hashCode both are implemented
- A recursive walker for the maze
- needs to keep track of locations already visited
- a natural use for a Set with contains
27Which to Use?
- Order of elements placed into the collection
matters. For example you want to get the items
out in the same order they were put in. - Use a List
- - see previous criteria
- If you often access by index in the list
- Use ArrayList
28Which to Use?
- If you want to access things that implement the
Comparable interface in sorted order according to
method compareTo - Use TreeSet
- If order is unimportant. You only need to know if
elements are in the collection or need to iterate
over elements in arbitrary order - Use a Set