Java Collections: Object-Oriented Programming
Java Collections: Object-Oriented Programming
Java Collections
Object-oriented programming
Inf1 :: 2005
Object-oriented programming
Java Collections
Java Collections
Collections
Data structures like the ones we discussed in the previous lectures are so important that the Java library provided a generic implementation
Package java.util
The collections framework is a perfect example of polymorphism, interfaces and object-oriented design
There is a basic interface (Collection) that all classes in java.util implement Behaviours are implemented in a variety of ways
Object-oriented programming
Java Collections
Java Collections
SortedSet Comparator comparator () Object rst () Object last () SortedSet headSet (Object to) SortedSet tailSet (Object from) SortedSet subset (Object from, Object to) AbstractSet
LinkedList Object getFirst () Object getLast () void addFirst (Object o) void addLast (Object o) Object removeFirst () Object removeLast ()
Object-oriented programming
Java Collections
Java Collections
In more detail
Collections are either Lists or Sets Lists are
Sequential Possibly with duplicate values Unordered with respect to the values they store
Sets are
Unordered with respect to the values Without any duplicate values
SortedSets are
Ordered (with respect to their values) Sets
Iterators are
A way of traversing all values in a Collection
ListIterators are
Special Iterators that allow one to traverse sequential Collections like Lists
Object-oriented programming Java Collections
Java Collections
Using a List
import everything from the java.util package (the collections framework)
private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public ListTest () { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.print("\nList: "); printList(list); System.out.print("\nReversed List: "); printReversedList(list); System.out.print("\nList from 5, forward: "); printListFromIndex(5, list); System.out.print("\nList from 5, backward: "); printReversedListFromIndex(5, list); }
List interface make the reference aim at a class that implements the interface (ArrayList) polymorphism ArrayLists implementation of add() will be called; add() is a Collection method and List extends Collection
Object-oriented programming
Java Collections
Java Collections
iterator declare an Iterator over the List, i.e., obtain a sequential handle over the Lists data; iterator() returns a ListIterator, which is an Iterator forward scan keep scanning forward, as long as the Iterator says there are more elements
list iterator declare a ListIterator over the List, since we want the extra functionality of scanning from a specic point
}
public void printReversedList (List l) { ListIterator iter = l.listIterator(l.size()); while (iter.hasPrevious()) System.out.print(iter.previous() + " "); System.out.println(); }
backward scan keep scanning backwards, as long as the ListIterator says there are more elements
Object-oriented programming
Java Collections
Java Collections
List: red white blue green gray orange tan white cyan peach gray orange Reversed List: orange gray peach cyan white tan orange gray green blue white red List from 5, forward: orange tan white cyan peach gray orange List from 5, backward: gray green blue white red
Object-oriented programming
Java Collections
Java Collections
Using a Set
import java.util.* imports the Collections framework
private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public SetTest () { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.print("\nArrayList: "); printCollection(list); Set hashSet = new HashSet(list); System.out.print("\nHashSet: "); printCollection(hashSet); }
reference to concrete class assign a List (interface) reference to an ArrayList concrete class (that implements the interface) create a set from a list use a Set (interface) reference to a HashSet concrete class (that implements the interface); use a list as the input collection
Object-oriented programming
Java Collections
Java Collections
Traversing a Set
Collection as parameter this will work for both Lists and Sets since they both extend Collection
public void printCollection (Collection c) { Iterator iter = c.iterator(); while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println(); }
Object-oriented programming
Java Collections
Java Collections
ArrayList: red white blue green gray orange tan white cyan peach gray orange HashSet: red cyan white tan gray green orange blue peach
Object-oriented programming
Java Collections
Java Collections
Using a SortedSet
import java.util.*; public class SortedSetTest { private static final String names[] = { "yellow", "green", "black", "tan", "grey", "white", "orange", "red", "green" }; public SortedSetTest () { SortedSet set = new TreeSet (); for (int i = 0; i < names.length; i++) set.add(names[i]); System.out.print("\nset: "); printSet(set); System.out.print("\nheadSet(\"orange\"): "); printSet(set.headSet("orange")); System.out.print("\ntailSet(\"orange\"): "); printSet(set.tailSet("orange")); System.out.print("\nheadSet(\"foo\"): "); printSet(set.headSet("foo")); System.out.print("\ntailSet(\"foo\"): "); printSet(set.tailSet("foo")); System.out.print("\nfirst: "); System.out.println(set.first()); System.out.print("\nlast: "); System.out.println(set.last()); }
SortedSet behaviour the methods called are SortedSet methods, but TreeSets implementations will be called
Object-oriented programming
Java Collections
Java Collections
SortedSet reference though a TreeSet instance will be passed as a parameter by the caller
public void printSet (SortedSet set) { Iterator iter = set.iterator(); while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println(); }
Object-oriented programming
Java Collections
Java Collections
set: black green grey orange red tan white yellow headSet("orange"): black green grey tailSet("orange"): orange red tan white yellow headSet("foo"): black tailSet("foo"): green grey orange red tan white yellow first: black last: yellow
Object-oriented programming
Java Collections
Java Collections
Provide generic implementations of certain functions Static method calls to invoke desired behaviour
Arrays.sort(array , value) Arrays.binarySearch(array , value) Collections.sort(Collection c) Collections.binarySearch(Collection c , Object o)
Object-oriented programming
Java Collections
Java Collections
Carried out with the aid of an object that implements the Comparator interface Main comparison method is: int compare (Object o1, Object o2)
If o1 < o2, then return a negative integer If o1 == o2, then return zero If o1 > o2, then return a positive integer
Object-oriented programming
Java Collections
Java Collections
A Time class
import java.text.DecimalFormat; public class Time { private int hour; private int minute; private int second; public Time () { this(0, 0, 0); } public Time (int h) { this(h, 0, 0); } public Time (int h, int m) { this(h, m, 0); } public Time (int h, int m, int s) { setTime(h, m, s); } public void setTime (int h, int m, int s) { setHour(h); setMinute(m); setSecond(s); } public void setHour (int h) { hour = ((h >= 0 || h < 24) ? h : 0); } public void setMinute (int m) { minute = ((m >= 0 || m < 60) ? m : 0); } public void setSecond (int s) { second = ((s >= 0 || s < 60) ? s : 0); } public int getHour () { return hour; } public int getMinute () { return minute; } public int getSecond () { return second; } public String toString () { DecimalFormat twoDigits = new DecimalFormat("00"); return twoDigits.format(hour) + ":" + twoDigits.format(minute) + ":" + twoDigits.format(second); } }
Object-oriented programming
Java Collections
Java Collections
A TimeComparator class
import simply import the necessary interface
import java.util.Comparator; public class TimeComparator implements Comparator { public TimeComparator () {} public int compare (Object o1, Object o2) { Time t1 = (Time) o1; Time t2 = (Time) o2; int comp = (t1.getHour() - t2.getHour()); if (comp != 0) return comp; comp = (t1.getMinute() - t2.getMinute()); if (comp != 0) return comp; comp = (t1.getSecond() - t2.getSecond()); return comp; } }
implementation specify which interface is implemented and provide an implementation for the methods of the interface cast TimeComparator can only handle Time objects; cast the parameters to Time (anything else will be a runtime error)
comparison make the comparison, at all times abiding by the semantics of the interface
Object-oriented programming Java Collections
Java Collections
System.out.print("unsorted list is: "); System.out.println(list); Collections.sort(list, new TimeComparator()); System.out.print("sorted list is: "); System.out.println(list); } }
unsorted list is: [06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22] sorted list is: [06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05]
Object-oriented programming
Java Collections
Java Collections
no need for a Comparator the class of the objects inserted in the list (String), already implements the Comparator interface Collections.binarySearch() pass a list and the object were looking for and were done!
unsorted list: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange] sorted list: [blue, cyan, gray, gray, green, orange, orange, peach, red, tan, white, white] gray first appears in position: 2 maroon first appears in position: -6
Object-oriented programming
Java Collections
Java Collections
Things to do
To do Read Deitel & Deitel, Sections 22.1, 22.2, 22.4, 22.5, 22.7 Become accustomed with the Java Collections framework Spend some time thinking on the differences between the various interfaces and classes
Object-oriented programming
Java Collections