Java Collections and Generics Object-oriented programming Inf1 :: - - PowerPoint PPT Presentation

java collections and generics
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

Java Collections Generics

Java Collections and Generics

Object-oriented programming Inf1 :: 2008

Object-oriented programming Java Collections and Generics

slide-2
SLIDE 2

Java Collections Generics

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

We will deal with lists, sets, iterators and trees

Object-oriented programming Java Collections and Generics

slide-3
SLIDE 3

Java Collections Generics

The class/interface hierarchy

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

slide-4
SLIDE 4

Java Collections Generics

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 and Generics

slide-5
SLIDE 5

Java Collections Generics

Using a List

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); }

import everything from the java.util package (the collections framework) List interface make the reference aim at a class that implements the interface (ArrayList) polymorphism ArrayList‘s implementation

  • f add() will be called;

add() is a Collection method and List extends Collection

Object-oriented programming Java Collections and Generics

slide-6
SLIDE 6

Java Collections Generics

Traversing a List with an Iterator

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

  • ver the List‘s 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 specific point backward scan keep scanning backwards, as long as the ListIterator says there are more elements Object-oriented programming Java Collections and Generics

slide-7
SLIDE 7

Java Collections Generics

Using a List — results

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

slide-8
SLIDE 8

Java Collections Generics

Using a Set

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); }

import java.util.* imports the Collections framework 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 and Generics

slide-9
SLIDE 9

Java Collections Generics

Traversing a Set

public void printCollection (Collection c) { Iterator iter = c.iterator(); while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println(); }

Collection as parameter this will work for both Lists and Sets since they both extend Collection

Object-oriented programming Java Collections and Generics

slide-10
SLIDE 10

Java Collections Generics

Using s Set — results

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

slide-11
SLIDE 11

Java Collections Generics

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()); }

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

slide-12
SLIDE 12

Java Collections Generics

Traversing a SortedSet through an Iterator

public void printSet (SortedSet set) { Iterator iter = set.iterator(); while (iter.hasNext()) System.out.print(iter.next() + " "); System.out.println(); }

SortedSet reference though a TreeSet instance will be passed as a parameter by the caller Collection behaviour a SortedSet is still a Collection so we can have an Iterator over it

Object-oriented programming Java Collections and Generics

slide-13
SLIDE 13

Java Collections Generics

Using s SortedSet — results

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

slide-14
SLIDE 14

Java Collections Generics

Classes Arrays and Collections

Provide generic implementations of certain functions Static method calls to invoke desired behaviour

Arrays.sort(array) Arrays.binarySearch(array , value) Collections.sort(Collection c) Collections.binarySearch(Collection c , Object o)

We will focus on Collections

Object-oriented programming Java Collections and Generics

slide-15
SLIDE 15

Java Collections Generics

Sorting and searching a List

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 and Generics

slide-16
SLIDE 16

Java Collections Generics

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 and Generics

slide-17
SLIDE 17

Java Collections Generics

A TimeComparator class

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; } }

import simply import the necessary interface implementation specify which interface is implemented and provide an implementation for the methods

  • f 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 and Generics

slide-18
SLIDE 18

Java Collections Generics

Sorting a List of Time objects

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); } }

static call Collections.sort() is a static method TimeComparator passed as the argument to sort(); becomes the sorting criterion

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

slide-19
SLIDE 19

Java Collections Generics

Sorting and searching a List of String objects

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

slide-20
SLIDE 20

Java Collections Generics

Things to do

To do Read Deitel & Deitel, Sections 19.1, 19.2, 19.4, 19.5, 19.6, 19.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 and Generics

slide-21
SLIDE 21

Java Collections Generics

Generics

When dealing with collections we have so far taken responsibility of what goes in a collection and what comes out

  • f a collection ourselves

All collections accepted Objects as elements When extracting an element from a collection, we had to cast it to the appropriate type

This is error prone as it is not type-safe

For instance, if we know that only a specific type should be used in a collection, it is preferable to ensure it at compile-time, rather than at run-time

Generics offer type safety without losing in terms of generality

Generic methods and generic classes Make the type itself a parameter of methods and classes Rely on the compiler to catch any type mismatches and translate the incomplete specification to a complete one

Object-oriented programming Java Collections and Generics

slide-22
SLIDE 22

Java Collections Generics

Standard technique: overloading

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(); }

Overloading For each type of array, provide an implementation for that type But the body of each method is always the same!

Object-oriented programming Java Collections and Generics

slide-23
SLIDE 23

Java Collections Generics

Generic method

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

slide-24
SLIDE 24

Java Collections Generics

Generic class

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

slide-25
SLIDE 25

Java Collections Generics

Using a generic class

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

slide-26
SLIDE 26

Java Collections Generics

Generic collections

The Java collections framework we have seen so far is completely generic That is, all classes can accept type parameters Though they can also be used in the standard way we have seen (Objects and casting)

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

slide-27
SLIDE 27

Java Collections Generics

No need for casting!

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

slide-28
SLIDE 28

Java Collections Generics

Things to do

To do Read Deitel & Deitel, Sections 18.1, 18.2, 18.3, 18.5, 18.6 Become accustomed with using the generic facets of the Java Collections framework Spend some time thinking about defining your own generic classes

Object-oriented programming Java Collections and Generics