Java Collections Generics
Java Collections and Generics
Object-oriented programming Inf1 :: 2008
Object-oriented programming Java Collections and Generics
Java Collections and Generics Object-oriented programming Inf1 :: - - PowerPoint PPT Presentation
Java Collections Generics Java Collections and Generics Object-oriented programming Inf1 :: 2008 Object-oriented programming Java Collections and Generics Java Collections Generics Collections Data structures like the ones we discussed in
Java Collections Generics
Object-oriented programming Java Collections and Generics
Java Collections Generics
Object-oriented programming Java Collections and Generics
Java Collections Generics
Collection boolean isEmpty () boolean add/remove (Object o) boolean add/removeAll (Collection c) void clear () boolean contains (Object o) boolean containsAll (Collection c) Iterator iterator () int size () Object [] toArray () List Object get (int index) Object set (int index, Object o) void add (int index, Object o) void addAll (int index, Collection c) Object remove (int index) int indexOf (Object o) int lastIndexOf (Object o) ListIterator listIterator () ListIterator listIterator (int index) List subList (int start, int end) AbstractList void removeRange (int start, int end) LinkedList Object getFirst () Object getLast () void addFirst (Object o) void addLast (Object o) Object removeFirst () Object removeLast () AbstractSequentialList ArrayList void ensureCapacity (int min) void trimToSize () Iterator boolean hasNext () Object next () void remove () ListIterator boolean hasPrevious () Object previous () int nextIndex () int previousIndex () Comparator int compare (Object o1, Object o2) Set SortedSet Comparator comparator () Object first () Object last () SortedSet headSet (Object to) SortedSet tailSet (Object from) SortedSet subset (Object from, Object to) TreeSet AbstractSet HashSet
Object-oriented programming Java Collections and Generics
Java Collections Generics
Object-oriented programming Java Collections and Generics
Java Collections Generics
import java.util.*; public class ListTest { 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); }
Object-oriented programming Java Collections and Generics
Java Collections Generics
public void printList (List l) { Iterator iter = l.iterator(); while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println(); } public void printReversedList (List l) { ListIterator iter = l.listIterator(l.size()); while (iter.hasPrevious()) System.out.print(iter.previous() + " "); System.out.println(); }
iterator declare an Iterator over the
List, i.e., obtain a sequential handle
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 specific point backward scan keep scanning backwards, as long as the ListIterator says there are more elements Object-oriented programming Java Collections and Generics
Java Collections Generics
import java.util.*; public class ListTest { 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: 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 and Generics
Java Collections Generics
import java.util.*; public class SetTest { 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); }
Object-oriented programming Java Collections and Generics
Java Collections Generics
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 and Generics
Java Collections Generics
import java.util.*; public class SetTest { 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); }
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 and Generics
Java Collections Generics
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()); }
polymorphism TreeSet implements SortedSet SortedSet behaviour the methods called are SortedSet methods, but TreeSet‘s implementations will be called
Object-oriented programming Java Collections and Generics
Java Collections Generics
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 and Generics
Java Collections Generics
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()); }
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 and Generics
Java Collections Generics
Object-oriented programming Java Collections and Generics
Java Collections Generics
Object-oriented programming Java Collections and Generics
Java Collections Generics
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 and Generics
Java Collections Generics
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; } }
Object-oriented programming Java Collections and Generics
Java Collections Generics
import java.util.*; public class CollectionSortTest { public static void main (String args []) { List list = new ArrayList(); list.add(new Time( 6, 24, 34)); list.add(new Time(18, 14, 5)); list.add(new Time( 8, 05, 0)); list.add(new Time(12, 07, 58)); list.add(new Time( 6, 14, 22)); 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 and Generics
Java Collections Generics
import java.util.*; public class CollectionSearchTest { private static final String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public static void main (String args []) { List list = new ArrayList(); for (int i = 0; i < colors.length; i++) list.add(colors[i]); System.out.println("unsorted list: " + list); Collections.sort(list); System.out.println("sorted list: " + list); int p = Collections.binarySearch(list, "gray"); System.out.println("gray first appears in position: " + p); p = Collections.binarySearch(list, "maroon"); System.out.println("maroon first appears in position: " + p); } }
no need for a Comparator the class of the objects inserted in the list (String), already implements the Comparator interface
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
Collections.binarySearch() pass a list and the object we’re looking for and we’re done! Object-oriented programming Java Collections and Generics
Java Collections Generics
Object-oriented programming Java Collections and Generics
Java Collections Generics
Object-oriented programming Java Collections and Generics
Java Collections Generics
public static void printArray (Integer [] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } public static void printArray (Character [] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } public static void printArray (Double [] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); }
Object-oriented programming Java Collections and Generics
Java Collections Generics
type parameter: this method accepts a type as a parameter, in addition to the standard method parameters method parameter is an array of elements of the type parameter three arrays of different types at compile-time the type parameter can be substituted with the correct type since the latter is known
public static <E> void genericPrintArray (E [] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } public static void main (String [] args) { Integer [] intArray = {1, 2, 3, 4, 5}; Double [] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5}; Character [] charArray = {'A', 'B', 'C', 'D', 'E'}; System.out.println("intArray from genericPrintArray()"); genericPrintArray(intArray); System.out.println("doubleArray from genericPrintArray()"); genericPrintArray(doubleArray); System.out.println("charArray from genericPrintArray()"); genericPrintArray(charArray); } Object-oriented programming Java Collections and Generics
Java Collections Generics
type parameters: this class takes two types as parameters usage: in the body of the class type parameters are used as standard types
public class Pair <F, S> { private F first; private S second; public Pair () { this(null, null); } public Pair (F f, S s) { first = f; second = s; } public F getFirst () { return first; } public S getSecond () { return second; } public String toString () { return "<first: " + first + ", second: " + second + ">"; } } Object-oriented programming Java Collections and Generics
Java Collections Generics
Pair.java:40: incompatible types found : java.lang.Integer required: java.lang.String String error = p2.getSecond(); ^ 1 error public static void main (String [] args) { Pair<String, String> p1 = new Pair<String, String>("aaa", "bbb"); Pair<String, Integer> p2 = new Pair<String, Integer>("aaa", 222); Pair<Double, String> p3 = new Pair<Double, String>(1.1, "bbb"); System.out.println("Pair 1 is " + p1); System.out.println("Pair 2 is " + p2); System.out.println("Pair 3 is " + p3); String s1 = p1.getSecond(); String s2 = p2.getFirst(); String s3 = p3.getSecond(); System.out.println("String 1 from Pair 1 is " + s1); System.out.println("String 2 from Pair 2 is " + s2); System.out.println("String 3 from Pair 3 is " + s3); //String error = p2.getSecond(); }
usage: provide concrete types for the class’s parameters when both declaring a reference and constructing an instance no need for casting; type information is known at compile-time errors like this can be caught when compiling the program Object-oriented programming Java Collections and Generics
Java Collections Generics
use type parameters as before
public class ListTest { private static final String [] colors = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public ListTest () { List<String> list = new ArrayList<String>(); 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); }
Object-oriented programming Java Collections and Generics
Java Collections Generics
specify type parameters; make sure the List and Iterator types are the same no need to cast the results of next() or previous(); the type is known at compile-time
public void printList (List<String> l) { Iterator<String> iter = l.iterator(); while (iter.hasNext()) { String s = iter.next(); System.out.print(s + " "); } System.out.println(); } public void printReversedList (List<String> l) { ListIterator<String> iter = l.listIterator(l.size()); while (iter.hasPrevious()) { String s = iter.previous(); System.out.print(s + " "); } System.out.println(); } Object-oriented programming Java Collections and Generics
Java Collections Generics
Object-oriented programming Java Collections and Generics