CISC6795, Spring 2011 Dr. Zhang Generics & Collections.
-
Upload
charlotte-walton -
Category
Documents
-
view
226 -
download
5
Transcript of CISC6795, Spring 2011 Dr. Zhang Generics & Collections.
CISC6795, Spring 2011Dr. Zhang
Generics & Collections
A sideline about arrayAn array: a sequence of either objects or
primitives that are all the same type and are packaged together under one identifier name.
Arrays are defined and used with the square brackets indexing operator [ ].
To define an array reference:int[] a1; //Preferred by some in Java community
Or put square brackets after identifier:int a1[]; //C/C++ style
The similarity between C and Java array ends here !
2
Initializing arrayUnlike in C/C++, Java does not allow
int a1[20];int a1[]; // declare a reference to an array
(memory is allocated for the reference), and there’s been no space allocated for the array object itself.
To create storage for the array, you must write an initialization expressionint[] a1 = { 1, 2, 3, 4, 5 };Compiler allocates storage allocation (equivalent
of using new) at this point. int[] a2=a1; // copying the reference,
3
Create array of primitive typesimport java.util.*;
import static net.mindview.util.Print.*;
public class ArrayNew {public static void main(String[] args) {
int[] a; // a reference to an array (of integer) objectRandom rand = new Random(47);a = new int[rand.nextInt(20)]; // create an array of size 20
integerprint("length of a = " + a.length);print(Arrays.toString(a));
}
} /* Output:
length of a = 18
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4
use new to create the elements in the array.
new works even though it’s creating an array of primitives
(new won’t create a non-array primitive)
Create array of non-primitive typesIf you create a non-primitive array, you
create an array of references:public class Inventory {
public Inventory ( )
{
items = new Item[5];
items[0] = new Item (1, "MEDIUM_PIZZA“, 1239, 0.0,10);
items[1] = new Item (2, "LARGE_PIZZA“, 1598, 0.0, 10);
5
items is only an array of references
new is called to create the array,
reference itself is initialized by creating
a new Item object
Outline: next two lessonsGenerics, new feature of J2SE 5.0
Provide compile-time type safety: catch invalid types at compile time
Generic methods: A single method declaration => a set of methods
Generic interfaces: A single interface declaration => a set of interface
Generic classes: A single class declaration => a set of classes
Java collections frameworkContain prepackaged data structures, interfaces, algorithmsUse existing data structures
Example of code reuseProvides reusable components
6
Motivation for Generic Methods
Overloaded methodsSimilar methods perform same operations on different
types of dataOverloaded printArray methods to print:
Integer arrayDouble arrayCharacter array
Only reference types can be used with generic methods/classes
Type-wrapper classes in package java.langEnable programmers to manipulate primitive-type values
as objectsBoolean, Byte, Character, Double, Float, Integer, Long
and Short7
Autoboxing and Auto-Unboxing Boxing conversion
Converts a value of a primitive type to an object of the corresponding type-wrapper class
From int to Integer, double to Double … Unboxing conversion
Converts an object of a type-wrapper class to a value of the corresponding primitive type
From Long to long, Float to float J2SE 5.0 automatically performs these
conversionsCalled autoboxing and auto-unboxing
8
Outline
1 // Fig. 18.1: OverloadedMethods.java
2 // Using overloaded methods to print array of different types.
3
4 public class OverloadedMethods
5 {
6 // method printArray to print Integer array
7 public static void printArray( Integer[] inputArray )
8 {
9 // display array elements
10 for ( Integer element : inputArray )
11 System.out.printf( "%s ", element );
12
13 System.out.println();
14 } // end method printArray
15
16 // method printArray to print Double array
17 public static void printArray( Double[] inputArray )
18 {
19 // display array elements
20 for ( Double element : inputArray )
21 System.out.printf( "%s ", element );
22
23 System.out.println();
24 } // end method printArray
25
9
Method printArray accepts an array of Integer objects
Method printArray accepts an array of Double objects
Outline26 // method printArray to print Character array
27 public static void printArray( Character[] inputArray )
28 {
29 // display array elements
30 for ( Character element : inputArray )
31 System.out.printf( "%s ", element );
32
33 System.out.println();
34 } // end method printArray
35
36 public static void main( String args[] )
37 {
38 // create arrays of Integer, Double and Character
39 Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
40 Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
41 Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
42
10
Method printArray accepts an array of Character objects
Auto-boxing happens here…
Outline43 System.out.println( "Array integerArray contains:" );
44 printArray( integerArray ); // pass an Integer array
45 System.out.println( "\nArray doubleArray contains:" );
46 printArray( doubleArray ); // pass a Double array
47 System.out.println( "\nArray characterArray contains:" );
48 printArray( characterArray ); // pass a Character array
49 } // end main
50 } // end class OverloadedMethods Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array characterArray contains: H E L L O
11
At compile time, compiler determines argument integerArray’s type (i.e., Integer[]), attempts to locate a method named printArray that specifies a single Integer[] parameter (lines 7-14)
Motivation for Generic Methods (Cont.)
The three printArray methods Array element type appears in two location
Method headerfor statement header
Combine three printArray methods into oneReplace element types with a generic name E
Declare one printArray methodDisplay string representation of the elements of
any array
12
Towards generic method 1 public static void printArray( E[] inputArray )
2 {
3 // display array elements
4 for ( E element : inputArray )
5 System.out.printf( "%s ", element );
6
7 System.out.println();
8 } // end method printArray
13
Replace the element type with a single generic type E
Actual syntax: public static < E > void printArrays( E[] array)
Type parameter section, also called formal type parametersDelimited by angle brackets ( < and > )Precede the method’s return typeContain one or more type parameters
Generic Methods: type parameterType parameter, also known as type variable
An identifier that specifies a generic type nameAct as placeholders for the types of the argument
passed to the generic method, i.e., actual type arguments
Usually use a capital letterConvention: use E (element) for a type parameter that
represents the type of an element in an array (or other collection)
Can be used in return type, parameter types and local variable typesCan be declared only once but can appear more than once: public static < E > void printTwoArrays( E[] array1, E[] array2 )
14
1 // Fig. 18.3: GenericMethodTest.java
2 // Using generic methods to print array of different types.
3
4 public class GenericMethodTest
5 {
6 // generic method printArray
7 public static < E > void printArray( E[] inputArray )
8 {
9 // display array elements
10 for ( E element : inputArray )
11 System.out.printf( "%s ", element );
12
13 System.out.println();
14 } // end method printArray
15
16 public static void main( String args[] )
17 {
18 // create arrays of Integer, Double and Character
19 Integer[] intArray = { 1, 2, 3, 4, 5 };
20 Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
21 Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
22
15
Type parameter section delimited by angle brackets (< and > )
Use the type parameter to declare method printArray’s parameter type
Use the type parameter to declare method printArray’s local variable type
23 System.out.println( "Array integerArray contains:" );
24 printArray( integerArray ); // pass an Integer array
25 System.out.println( "\nArray doubleArray contains:" );
26 printArray( doubleArray ); // pass a Double array
27 System.out.println( "\nArray characterArray contains:" );
28 printArray( characterArray ); // pass a Character array
29 } // end main
30 } // end class GenericMethodTest Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array characterArray contains: H E L L O
16
Invoke generic method printArray with an Integer array
Invoke generic method printArray with a Character array
Questions/ExercisesA generic method that find the maximum
value in an array? Problem: need to make sure the type is
comparable… Objects o1, and o2 of the type can be
compared, using o1.compareTo (o2) …Need to say the type is any type that provides
compareTo() method Interface ? But the parameter of compareTo is
type specific, …=> generic interface, an parameterized
interface
17
OutlineGenerics, new feature of J2SE 5.0
Provide compile-time type safety: catch invalid types at compile time
Generic methods: A single method declaration => a set of related methods
Generic interface: a single interface declaration=> a set of related interface
Generic classes: A single class declaration => a set of related classes
Java collections framework, use generics Contain prepackaged data structures, interfaces, algorithmsUse existing data structures
Example of code reuseProvides reusable components
18
Generic Interface: Comparable
public interface Comparable<T>
{
int compareTo(T other);
}compareTo(): Compare two objects (this and other) of
type T Return 0 if two objects are equal Return -1 if this is less than other Return 1 if this is greater than other
imposes a total ordering, or natural ordering on the objects of each class that implements it.
natural ordering is consistent with equals if and only if: (e1.compareTo(e2) == 0) <=> e1.equals(e2) for every e1 and
e2 of class C.
19
Generic Interface: Comparablepublic interface Comparable<T>
{
int compareTo(T o);
}
Lists (and arrays) of objects that implement this interface can be sorted using Collections.sort (and Arrays.sort).
Objects that implement this interface can be used as keys in a sorted map or elements in a sorted set
20
Upper bound of type parameterNext example, generic method
maximum (x,y,z)Call compareTo method to compare two
objects Actual type must implement Comparable
interface
21
1 // Fig. 18.5: MaximumTest.java
2 // Generic method maximum returns the largest of three objects.
3
4 public class MaximumTest
5 {
6 // determines the largest of three Comparable objects
7 public static < T extends Comparable< T > > T maximum( T x, T y, T z )
8 {
9 T max = x; // assume x is initially the largest
10
11 if ( y.compareTo( max ) > 0 )
12 max = y; // y is the largest so far
13
14 if ( z.compareTo( max ) > 0 )
15 max = z; // z is the largest
16
17 return max; // returns the largest object
18 } // end method maximum
19
22
only object of classes that implement interface Comparable can be used
Type parameter is used in the return type of method maximum
Invokes method compareTo method Comparable to compare z and max
Generic interface: with a single interface declaration, a set of related typesE.g., Comparable< T >, all types that implement interface Comparable
Outline20 public static void main( String args[] )
21 {
22 System.out.printf( "Maximum of %d, %d and %d is %d\n\n", 3, 4, 5,
23 maximum( 3, 4, 5 ) );
24 System.out.printf( "Maximum of %.1f, %.1f and %.1f is %.1f\n\n",
25 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
26 System.out.printf( "Maximum of %s, %s and %s is %s\n", "pear",
27 "apple", "orange", maximum( "pear", "apple", "orange" ) );
28 } // end main 29 } // end class MaximumTest
Maximum of 3, 4 and 5 is 5 Maximum of 6.6, 8.8 and 7.7 is 8.8 Maximum of pear, apple and orange is pear
23
Invoke generic method maximum with three strings
Compile-Time TranslationUpper bound of type parameter: constraints on
actual typeDefault is Objectuse keyword extends to specify
E.g., T extends Comparable< T >
When compiler translates generic method to Java bytecodeReplaces type parameter with its upper boundInsert explicit cast operatione.g., line 23 of Fig. 18.5 I preceded by an Integer
cast(Integer) maximum( 3, 4, 5 )
24
Erasure
1 public static Comparable maximum(Comparable x, Comparable y, Comparable z)
2 {
3 Comparable max = x; // assume x is initially the largest
4
5 if ( y.compareTo( max ) > 0 )
6 max = y; // y is the largest so far
7
8 if ( z.compareTo( max ) > 0 )
9 max = z; // z is the largest
10
11 return max; // returns the largest object
12 } // end method maximum
25
Erasure replaces type parameter T with its upper bound Comparable
1 public static void printArray( Object[] inputArray )
2 {
3 // display array elements
4 for ( Object element : inputArray )
5 System.out.printf( "%s ", element );
6
7 System.out.println();
8 } // end method printArray
Overloading Generic MethodGeneric method may be overloaded
By another generic methodSame method name but different method parameters
By non-generic methodsSame method name and number of parameters
When compiler encounters a method callSearch for most precise matching method first
Exact method name and argument typesThen search for inexact but applicable matching
methodExercise:
Write a generic method bubbleSort based on your lab3
26
OutlineGenerics, new feature of J2SE 5.0
Provide compile-time type safety: catch invalid types at compile time
Generic methods: A single method declaration => a set of related methods
Generic classes: A single class declaration => a set of related classes
Java collections framework, use generics Contain prepackaged data structures, interfaces,
algorithmsUse existing data structures
Example of code reuseProvides reusable components
27
Generic ClassesGeneric classes, parameterized classes, also called
parameterized typesGeneric class declaration, looks like a non-generic
class declaration, except class name is followed by a type parameter sectiona simple, concise notation to indicate the actual
type(s)We study generic class Stack that implements basic
stack operations: push a new element onto stack, pop an element from stack,…, independent of the actual element typeInstantiate a stack of different element type: e.g., Stack< Double >, Stack<Integer>, Stack<Item>
28
1 // Fig. 18.7: Stack.java
2 // Generic class Stack.
3
4 public class Stack< E >
5 {
6 private final int size; // number of elements in the stack
7 private int top; // location of the top element
8 private E[] elements; // array that stores stack elements
9
10 // no-argument constructor creates a stack of the default size
11 public Stack()
12 {
13 this( 10 ); // default stack size
14 } // end no-argument Stack constructor
15
16 // constructor creates a stack of the specified number of elements
17 public Stack( int s )
18 {
19 size = s > 0 ? s : 10; // set size of Stack
20 top = -1; // Stack initially empty
21
22 elements = ( E[] ) new Object[ size ]; // create array
23 } // end Stack constructor
24
29
Generic class declaration, class name is followed by a type parameter section
Declare elements as an array that stores objects of type E
Create an array of type E. The generic mechanism does not allow type parameter in array-creation expressions because the type parameter is not available at runtime
Outline25 // push element onto stack; if successful, return true;
26 // otherwise, throw FullStackException
27 public void push( E pushValue )
28 {
29 if ( top == size - 1 ) // if stack is full
30 throw new FullStackException( String.format(
31 "Stack is full, cannot push %s", pushValue ) );
32
33 elements[ ++top ] = pushValue; // place pushValue on Stack
34 } // end method push
35
36 // return the top element if not empty; else throw EmptyStackException
37 public E pop()
38 {
39 if ( top == -1 ) // if stack is empty
40 throw new EmptyStackException( "Stack is empty, cannot pop" );
41
42 return elements[ top-- ]; // remove and return top element of Stack
43 } // end method pop
44 } // end class Stack< E >
30
Method push pushes element of type E onto stack
Method pop returns the top element, which is of type E
1 // Fig. 18.8: FullStackException.java
2 // Indicates a stack is full.
3 public class FullStackException extends RuntimeException
4 {
5 // no-argument constructor
6 public FullStackException()
7 {
8 this( "Stack is full" );
9 } // end no-argument FullStackException constructor
10
11 // one-argument constructor
12 public FullStackException( String exception )
13 {
14 super( exception );
15 } // end one-argument FullStackException constructor
16 } // end class FullStackException
31
Outline 1 // Fig. 18.9: EmptyStackException.java
2 // Indicates a stack is full.
3 public class EmptyStackException extends RuntimeException
4 {
5 // no-argument constructor
6 public EmptyStackException()
7 {
8 this( "Stack is empty" );
9 } // end no-argument EmptyStackException constructor
10
11 // one-argument constructor
12 public EmptyStackException( String exception )
13 {
14 super( exception );
15 } // end one-argument EmptyStackException constructor
16 } // end class EmptyStackException
32
Generic Classes (Cont.)Generic class at compilation time
Compiler performs erasure on class’s type parameters
Compiler replaces type parameters with their upper bounds
Generic class test program at compilation timeCompiler performs type checkingCompiler inserts cast operations as
necessary
33
1 // Fig. 18.10: StackTest.java
2 // Stack generic class test program.
3
4 public class StackTest
5 {
6 private double[] doubleElements = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 };
7 private int[] integerElements = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
8
9 private Stack< Double > doubleStack; // stack stores Double objects
10 private Stack< Integer > integerStack; // stack stores Integer objects
11
12 // test Stack objects
13 public void testStacks()
14 {
15 doubleStack = new Stack< Double >( 5 ); // Stack of Doubles
16 integerStack = new Stack< Integer >( 10 ); // Stack of Integers
17
18 testPushDouble(); // push double onto doubleStack
19 testPopDouble(); // pop from doubleStack
20 testPushInteger(); // push int onto intStack
21 testPopInteger(); // pop from intStack
22 } // end method testStacks
23
34
Generic class Stack’s type argument is Double
Generic class Stack’s type argument is Integer
Instantiate object doubleStack of size 5 and ingeterStack of size 10
Outline24 // test push method with double stack
25 public void testPushDouble()
26 {
27 // push elements onto stack
28 try
29 {
30 System.out.println( "\nPushing elements onto doubleStack" );
31
32 // push elements to Stack
33 for ( double element : doubleElements )
34 {
35 System.out.printf( "%.1f ", element );
36 doubleStack.push( element ); // push onto doubleStack
37 } // end for
38 } // end try
39 catch ( FullStackException fullStackException )
40 {
41 System.err.println();
42 fullStackException.printStackTrace();
43 } // end catch FullStackException
44 } // end method testPushDouble
45
35
Invoke Stack’s method push to place a double value onto doubleStack
46 // test pop method with double stack
47 public void testPopDouble()
48 {
49 // pop elements from stack
50 try
51 {
52 System.out.println( "\nPopping elements from doubleStack" );
53 double popValue; // store element removed from stack
54
55 // remove all elements from Stack
56 while ( true )
57 {
58 popValue = doubleStack.pop(); // pop from doubleStack
59 System.out.printf( "%.1f ", popValue );
60 } // end while
61 } // end try
62 catch( EmptyStackException emptyStackException )
63 {
64 System.err.println();
65 emptyStackException.printStackTrace();
66 } // end catch EmptyStackException
67 } // end method testPopDouble
68
36
Auto-unboxing occurs when the value returned by pop (Double) is assigned to a double primitive variable
Outline69 // test push method with integer stack
70 public void testPushInteger()
71 {
72 // push elements to stack
73 try
74 {
75 System.out.println( "\nPushing elements onto intStack" );
76
77 // push elements to Stack
78 for ( int element : integerElements )
79 {
80 System.out.printf( "%d ", element );
81 integerStack.push( element ); // push onto integerStack
82 } // end for
83 } // end try
84 catch ( FullStackException fullStackException )
85 {
86 System.err.println();
87 fullStackException.printStackTrace();
88 } // end catch FullStackException
89 } // end method testPushInteger
90
37
Invoke Stack’s method push to place an int value onto integerStack
Outline91 // test pop method with integer stack
92 public void testPopInteger()
93 {
94 // pop elements from stack
95 try
96 {
97 System.out.println( "\nPopping elements from intStack" );
98 int popValue; // store element removed from stack
99
100 // remove all elements from Stack
101 while ( true )
102 {
103 popValue = integerStack.pop(); // pop from intStack
104 System.out.printf( "%d ", popValue );
105 } // end while
106 } // end try
107 catch( EmptyStackException emptyStackException )
108 {
109 System.err.println();
110 emptyStackException.printStackTrace();
111 } // end catch EmptyStackException
112 } // end method testPopInteger
113
114 public static void main( String args[] )
115 {
116 StackTest application = new StackTest();
117 application.testStacks();
118 } // end main
119 } // end class StackTest
38
Auto-unboxing occurs when the value returned by pop (Integer) is assigned to an int primitive variable
Outline Pushing elements onto doubleStack 1.1 2.2 3.3 4.4 5.5 6.6 FullStackException: Stack is full, cannot push 6.6 at Stack.push(Stack.java:30) at StackTest.testPushDouble(StackTest.java:36) at StackTest.testStacks(StackTest.java:18) at StackTest.main(StackTest.java:117) Popping elements from doubleStack 5.5 4.4 3.3 2.2 1.1 EmptyStackException: Stack is empty, cannot pop at Stack.pop(Stack.java:40) at StackTest.testPopDouble(StackTest.java:58) at StackTest.testStacks(StackTest.java:19) at StackTest.main(StackTest.java:117) Pushing elements onto integerStack 1 2 3 4 5 6 7 8 9 10 11 FullStackException: Stack is full, cannot push 11 at Stack.push(Stack.java:30) at StackTest.testPushInteger(StackTest.java:81) at StackTest.testStacks(StackTest.java:20) at StackTest.main(StackTest.java:117) Popping elements from integerStack 10 9 8 7 6 5 4 3 2 1 EmptyStackException: Stack is empty, cannot pop at Stack.pop(Stack.java:40) at StackTest.testPopInteger(StackTest.java:103) at StackTest.testStacks(StackTest.java:21) at StackTest.main(StackTest.java:117)
39
Generic Classes (Cont.)Creating generic methods to test class Stack< E >Method testPush
Perform same tasks as testPushDouble and testPushInteger
Method testPopPerform same tasks as testPopDouble and testPopInteger
40
Outline 1 // Fig. 18.11: StackTest2.java
2 // Stack generic class test program.
3
4 public class StackTest2
5 {
6 private Double[] doubleElements = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 };
7 private Integer[] integerElements =
8 { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
9
10 private Stack< Double > doubleStack; // stack stores Double objects
11 private Stack< Integer > integerStack; // stack stores Integer objects
12
13 // test Stack objects
14 public void testStacks()
15 {
16 doubleStack = new Stack< Double >( 5 ); // Stack of Doubles
17 integerStack = new Stack< Integer >( 10 ); // Stack of Integers
18
19 testPush( "doubleStack", doubleStack, doubleElements );
20 testPop( "doubleStack", doubleStack );
21 testPush( "integerStack", integerStack, integerElements );
22 testPop( "integerStack", integerStack );
23 } // end method testStacks
24
41
Invoke generic methods testPush and testPop to push elements onto stack and pop elements from stack
Outline25 // generic method testPush pushes elements onto a Stack
26 public < T > void testPush( String name, Stack< T > stack,
27 T[] elements )
28 {
29 // push elements onto stack
30 try
31 {
32 System.out.printf( "\nPushing elements onto %s\n", name );
33
34 // push elements onto Stack
35 for ( T element : elements )
36 {
37 System.out.printf( "%s ", element );
38 stack.push( element ); // push element onto stack
39 }
40 } // end try
41 catch ( FullStackException fullStackException )
42 {
43 System.out.println();
44 fullStackException.printStackTrace();
45 } // end catch FullStackException
46 } // end method testPush
47
42
Generic method testPush replaces testPushDouble and testPushInteger
Replace element type Double/Integer with type parameter T
Outline
48 // generic method testPop pops elements from a Stack
49 public < T > void testPop( String name, Stack< T > stack )
50 {
51 // pop elements from stack
52 try
53 {
54 System.out.printf( "\nPopping elements from %s\n", name );
55 T popValue; // store element removed from stack
56
57 // remove elements from Stack
58 while ( true )
59 {
60 popValue = stack.pop(); // pop from stack
61 System.out.printf( "%s ", popValue );
62 } // end while
63 } // end try
64 catch( EmptyStackException emptyStackException )
65 {
66 System.out.println();
67 emptyStackException.printStackTrace();
68 } // end catch EmptyStackException
69 } // end method testPop
70
71 public static void main( String args[] )
72 {
73 StackTest2 application = new StackTest2();
74 application.testStacks();
75 } // end main
76 } // end class StackTest2
43
Generic method testPop replaces testPopDouble and testPopInteger
Replace element type Double/Integer with type parameter T
Outline Pushing elements onto doubleStack 1.1 2.2 3.3 4.4 5.5 6.6 FullStackException: Stack is full, cannot push 6.6 at Stack.push(Stack.java:30) at StackTest2.testPush(StackTest2.java:38) at StackTest2.testStacks(StackTest2.java:19) at StackTest2.main(StackTest2.java:74) Popping elements from doubleStack 5.5 4.4 3.3 2.2 1.1 EmptyStackException: Stack is empty, cannot pop at Stack.pop(Stack.java:40) at StackTest2.testPop(StackTest2.java:60) at StackTest2.testStacks(StackTest2.java:20) at StackTest2.main(StackTest2.java:74) Pushing elements onto integerStack 1 2 3 4 5 6 7 8 9 10 11 FullStackException: Stack is full, cannot push 11 at Stack.push(Stack.java:30) at StackTest2.testPush(StackTest2.java:38) at StackTest2.testStacks(StackTest2.java:21) at StackTest2.main(StackTest2.java:74) Popping elements from integerStack 10 9 8 7 6 5 4 3 2 1 EmptyStackException: Stack is empty, cannot pop at Stack.pop(Stack.java:40) at StackTest2.testPop(StackTest2.java:60) at StackTest2.testStacks(StackTest2.java:22) at StackTest2.main(StackTest2.java:74)
44
OutlineGenerics, new feature of J2SE 5.0
Provide compile-time type safety: catch invalid types at compile time
Generic methods: A single method declaration => a set of related methods
Generic classes: A single class declaration => a set of related classes
Data Structure: linked listJava collections framework, use generics Contain prepackaged data structures, interfaces, algorithmsUse existing data structures
Example of code reuseProvides reusable components
45
Primer on Data structure
*
46
How to store a collection of data
Array: fixed-size data structure for holding reference to objects with same typecannot grow and shrink at execution time
Dynamic data structure: Linked list: collection of data items that link
up in a chain
Tree: collection of data items that form a tree
47
48
Linked listSelf-referential class: contains an instance
variable that refers to another object of the same class type, called a linkDrawn as an line with arrow pointing to the
other objectA null reference indicates that the link does
not refer to another object (drawn as a backslash in diagram)
Diagram of a linked list
linkdata
49
List.java (1 of 6)
1 // Fig. 17.3: List.java
2 // ListNode and List class definitions.
3 package com.deitel.jhtp6.ch17;
4
5 // class to represent one node in a list
6 class ListNode
7 {
8 // package access members; List can access these directly
9 Object data;
10 ListNode nextNode;
11
12 // constructor creates a ListNode that refers to object
13 ListNode( Object object )
14 {
15 this( object, null );
16 } // end ListNode one-argument constructor
17
18 // constructor creates ListNode that refers to
19 // Object and to next ListNode
20 ListNode( Object object, ListNode node )
21 {
22 data = object;
23 nextNode = node;
24 } // end ListNode two-argument constructor 25
Field data can refer to any object
Stores a reference to the next ListNode object in the linked list
50
Outline
List.java (2 of 6)
26 // return reference to data in node
27 Object getObject()
28 {
29 return data; // return Object in this node
30 } // end method getObject
31
32 // return reference to next node in list
33 ListNode getNext()
34 {
35 return nextNode; // get next node
36 } // end method getNext
37 } // end class ListNode
38
39 // class List definition
40 public class List
41 {
42 private ListNode firstNode;
43 private ListNode lastNode;
44 private String name; // string like "list" used in printing
45
46 // constructor creates empty List with "list" as the name
47 public List()
48 {
49 this( "list" );
50 } // end List no-argument constructor 51
References to the first and last ListNodes in a List
Call one-argument constructor
51
List.java (3 of 6)
52 // constructor creates an empty List with a name
53 public List( String listName )
54 {
55 name = listName;
56 firstNode = lastNode = null;
57 } // end List one-argument constructor
58
59 // insert Object at front of List
60 public void insertAtFront( Object insertItem )
61 {
62 if ( isEmpty() ) // firstNode and lastNode refer to same object
63 firstNode = lastNode = new ListNode( insertItem );
64 else // firstNode refers to new node
65 firstNode = new ListNode( insertItem, firstNode );
66 } // end method insertAtFront
67
68 // insert Object at end of List
69 public void insertAtBack( Object insertItem )
70 {
71 if ( isEmpty() ) // firstNode and lastNode refer to same Object
72 firstNode = lastNode = new ListNode( insertItem );
73 else // lastNode's nextNode refers to new node
74 lastNode = lastNode.nextNode = new ListNode( insertItem );
75 } // end method insertAtBack 76
Initialize both references to null
Order of evaluation?
52
List.java (4 of 6)
77 // remove first node from List
78 public Object removeFromFront() throws EmptyListException
79 {
80 if ( isEmpty() ) // throw exception if List is empty
81 throw new EmptyListException( name );
82
83 Object removedItem = firstNode.data; // retrieve data being removed
84
85 // update references firstNode and lastNode
86 if ( firstNode == lastNode )
87 firstNode = lastNode = null;
88 else
89 firstNode = firstNode.nextNode;
90
91 return removedItem; // return removed node data
92 } // end method removeFromFront
93
94 // remove last node from List
95 public Object removeFromBack() throws EmptyListException
96 {
97 if ( isEmpty() ) // throw exception if List is empty
98 throw new EmptyListException( name );
99
100 Object removedItem = lastNode.data; // retrieve data being removed 101
53
Outline
List.java (5 of 6)
102 // update references firstNode and lastNode
103 if ( firstNode == lastNode )
104 firstNode = lastNode = null;
105 else // locate new last node
106 {
107 ListNode current = firstNode;
108
109 // loop while current node does not refer to lastNode
110 while ( current.nextNode != lastNode )
111 current = current.nextNode;
112
113 lastNode = current; // current is new lastNode
114 current.nextNode = null;
115 } // end else
116
117 return removedItem; // return removed node data
118 } // end method removeFromBack
119
120 // determine whether list is empty
121 public boolean isEmpty()
122 {
123 return firstNode == null; // return true if List is empty
124 } // end method isEmpty 125
Predicate method that determines whether the list is empty
54
Outline
List.java (6 of 6)
126 // output List contents
127 public void print()
128 {
129 if ( isEmpty() )
130 {
131 System.out.printf( "Empty %s\n", name );
132 return;
133 } // end if
134
135 System.out.printf( "The %s is: ", name );
136 ListNode current = firstNode;
137
138 // while not at end of list, output current node's data
139 while ( current != null )
140 {
141 System.out.printf( "%s ", current.data );
142 current = current.nextNode;
143 } // end while
144
145 System.out.println( "\n" );
146 } // end method print
147 } // end class List
Display the list’s contents
Output a string representation of current.data
Move to the next node in the list
55
EmptyListException.java
1 // Fig. 17.4: EmptyListException.java
2 // Class EmptyListException definition.
3 package com.deitel.jhtp6.ch17;
4
5 public class EmptyListException extends RuntimeException
6 {
7 // no-argument constructor
8 public EmptyListException()
9 {
10 this( "List" ); // call other EmptyListException constructor
11 } // end EmptyListException no-argument constructor
12
13 // one-argument constructor
14 public EmptyListException( String name )
15 {
16 super( name + " is empty" ); // call superclass constructor
17 } // end EmptyListException one-argument constructor
18 } // end class EmptyListException
An unchecked exception
Outline 1 // Fig. 17.5: ListTest.java
2 // ListTest class to demonstrate List capabilities.
3 import com.deitel.jhtp6.ch17.List;
4 import com.deitel.jhtp6.ch17.EmptyListException;
5
6 public class ListTest
7 {
8 public static void main( String args[] )
9 {
10 List list = new List(); // create the List container
11
12 // insert integers in list
13 list.insertAtFront( -1 );
14 list.print();
15 list.insertAtFront( 0 );
16 list.print();
17 list.insertAtBack( 1 );
18 list.print();
19 list.insertAtBack( 5 );
20 list.print(); 21
56
57
22 // remove objects from list; print after each removal
23 try
24 {
25 Object removedObject = list.removeFromFront();
26 System.out.printf( "%s removed\n", removedObject );
27 list.print();
28
29 removedObject = list.removeFromFront();
30 System.out.printf( "%s removed\n", removedObject );
31 list.print();
32
33 removedObject = list.removeFromBack();
34 System.out.printf( "%s removed\n", removedObject );
35 list.print();
36
37 removedObject = list.removeFromBack();
38 System.out.printf( "%s removed\n", removedObject );
39 list.print();
40 } // end try
41 catch ( EmptyListException emptyListException )
42 {
43 emptyListException.printStackTrace();
44 } // end catch
45 } // end main
46 } // end class ListTest
58
Trees Trees:
Has a single root nodeEach node has multiple links,
each referring to a child nodeLeft child is the root of the left
subtreeRight child is the root of the
right subtreeSiblings are the children of a
specific nodeA leaf node has no children,
i.e., null links
59
Trees (Cont.)Binary search trees
Value stores in a node, Larger than values stored in its left
subtree Smaller than values stored in its right
subtree
Searching is easy: Compare value to search for with
rootIf smaller, goes to left subtree; if
larger, goes to right subtree; if same, return found …
Other algorithms: traversing a tree: inorder,
preorder, postorder
Abstract Data Structure (ADT)Many applications need to use collections with access
constraintsList: a collection of data stored in certain order
where insertion and deletion can be made any where in the orderE.g. Insert an element at the 5th position
Stack: insertion and deletion are made at one end only, i.e., topUsed in compiler, operating system
Queue: insertion made at one end (tail) and deletion made at another end (head)
Implementation details are hiddenCan use array or linked list to implement above ADT
60
61
Stacks Stacks, Last-in, first-out (LIFO) data structure
Method push adds a new node to the top of the stack
Method pop removes a node from the top of the stack and returns the data from the popped node
Application example: Program execution stack
Holds the return addresses , local variables and parameters of method invocation
Used by the compiler to evaluate arithmetic expressions
62
Stack Implementation option 1Stack class that inherits from List
Stack methods push, pop, isEmpty and print are performed by inherited methods insertAtFront, removeFromFront, isEmpty and printpush calls insertAtFrontpop calls removeFromFrontisEmpty and print can be called as inherited
Other List methods are also inheritedIncluding methods that should not be in the stack
class’s public interface
63
Stacks implementation option 2Stack class that contains a reference to a ListEach stack method invoked delegates the
call to the appropriate List methodmethod push delegates to List method insertAtFront
method pop delegates to List method removeFromFront
method isEmpty delegates to List method isEmptymethod print delegates to List method print
Enables us to hide the List methods that should not be in our stack’s public interface
Outline 1 // Fig. 17.12: StackComposition.java
2 // Class StackComposition definition with composed List object.
3 package com.deitel.jhtp6.ch17;
4
5 public class StackComposition
6 {
7 private List stackList;
8
9 // no-argument constructor
10 public StackComposition()
11 {
12 stackList = new List( "stack" );
13 } // end StackComposition no-argument constructor
14
15 // add object to stack
16 public void push( Object object )
17 {
18 stackList.insertAtFront( object );
19 } // end method push 20
64
private List reference
push method delegates call to List method insertAtFront
Outline21 // remove object from stack
22 public Object pop() throws EmptyListException
23 {
24 return stackList.removeFromFront();
25 } // end method pop
26
27 // determine if stack is empty
28 public boolean isEmpty()
29 {
30 return stackList.isEmpty();
31 } // end method isEmpty
32
33 // output stack contents
34 public void print()
35 {
36 stackList.print();
37 } // end method print
38 } // end class StackComposition
65
Method pop delegates call to List method removeFromFront
Method isEmpty delegates call to List method isEmpty
Method print delegates call to List method print
66
Queues Queue, First-in, first-out (FIFO) data structureSimilar to a checkout line in a supermarket
Enqueue: inserts nodes at the tail (or end)Dequeue: removes nodes from the head (or front)
Application example:Used to support print spooling: a spooler
program manages the queue of printing jobsMulti-thread programming: a pool of thread, a
queue of tasks
67
Queues implementationQueue class that contains a reference to a ListMethod enqueue calls List method insertAtBack
Method dequeue calls List method removeFromFront
Method isEmpty calls List method isEmptyMethod print calls List method print
Outline 1 // Fig. 17.13: Queue.java
2 // Class Queue.
3 package com.deitel.jhtp6.ch17;
4
5 public class Queue
6 {
7 private List queueList;
8
9 // no-argument constructor
10 public Queue()
11 {
12 queueList = new List( "queue" );
13 } // end Queue no-argument constructor
14
15 // add object to queue
16 public void enqueue( Object object )
17 {
18 queueList.insertAtBack( object );
19 } // end method enqueue 20
68
An object of class List
Method enqueue calls List method insertAtBack
Outline21 // remove object from queue
22 public Object dequeue() throws EmptyListException
23 {
24 return queueList.removeFromFront();
25 } // end method dequeue
26
27 // determine if queue is empty
28 public boolean isEmpty()
29 {
30 return queueList.isEmpty();
31 } // end method isEmpty
32
33 // output queue contents
34 public void print()
35 {
36 queueList.print();
37 } // end method print
38 } // end class Queue
69
Method dequeue calls List method removeFromFront
Outline 1 // Fig. 17.14: QueueTest.java
2 // Class QueueTest.
3 import com.deitel.jhtp6.ch17.Queue;
4 import com.deitel.jhtp6.ch17.EmptyListException;
5
6 public class QueueTest
7 {
8 public static void main( String args[] )
9 {
10 Queue queue = new Queue();
11
12 // use enqueue method
13 queue.enqueue( -1 );
14 queue.print();
15 queue.enqueue( 0 );
16 queue.print();
17 queue.enqueue( 1 );
18 queue.print();
19 queue.enqueue( 5 );
20 queue.print(); 21
70
Create a Queue object
Enqueue four integers
71
22 // remove objects from queue
23 try
24 {
25 Object removedObject = null;
26
27 while ( true )
28 {
29 removedObject = queue.dequeue(); // use dequeue method
30 System.out.printf( "%s dequeued\n", removedObject );
31 queue.print();
32 } // end while
33 } // end try
34 catch ( EmptyListException emptyListException )
35 {
36 emptyListException.printStackTrace();
37 } // end catch
38 } // end main
39 } // end class QueueTest
Dequeue the objects in first-in, first-out order
Display the exception’s stack trace
Outline The queue is: -1 The queue is: -1 0 The queue is: -1 0 1 The queue is: -1 0 1 5 -1 dequeued The queue is: 0 1 5 0 dequeued The queue is: 1 5 1 dequeued The queue is: 5 5 dequeued Empty queue com.deitel.jhtp6.ch17.EmptyListException: queue is empty at com.deitel.jhtp6.ch17.List.removeFromFront(List.java:81) at com.deitel.jhtp6.ch17.Queue.dequeue(Queue.java:24) at QueueTest.main(QueueTest.java:29)
72
End of primer
73
Java Collections FrameworkA unified architecture for representing and
manipulating collections. It contains: Interfaces: abstract data types that represent
collections. Interfaces allow collections to be manipulated independently of the details of their representation.
Implementations: concrete implementations of collection interfaces. They are reusable data structures.
Algorithms: methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces.polymorphic: same method can be used on many different
implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.
74
Some collection framework interfaces
75
Java Collections Framework: enhanced with generics capabilities in J2SE 5.0
Allow one to declare a stack of Card, a queue of Customers, using the type parameter
Compile-time type checking ensure only objects of given type can be stored into the collection
Object retrieved from the collection is cast to appropriate type
In comparison, implementation of stack/queue seen so far store a collection of Object
One can store different objects into it Programmer needs to cast the object retrieved to its
original type …
Java Collection Framework: Interfaces Hierarchy
76
These interfaces allow collections to be manipulated independently
of the details of their representation.
Collection Interface hierarchyCollection interface: basic functionality used by all
collections, such as add and remove methodsSet interface: does not allow duplicate elements
useful for storing collections such as a deck of cards or student records.
a subinterface, SortedSet, provides for ordering of elements
List interface: an ordered collection, provides precise control over where each element is inserted or retrieved from
Queue interface: additional insertion, extraction, and inspection operations. elements in a Queue are typically ordered in on a FIFO
basis.
77
Collection Interface hierarchy (2)Map interface: maps keys and values
similar to a Hashtable.Map's subinterface, SortedMap, maintains its
key-value pairs in ascending order or in an order specified by a Comparator.
78
Collection Interfaces are generic
All core collection interfaces are generic. E.g, the declaration of the Collection interface:public interface Collection<E>... The <E> syntax tells you that the interface is
generic. When you declare a Collection instance you
can and should specify the type of object contained in the collection. Allow compiler to verify (at compile-time) that
the type of object you put into the collection is correct, reducing errors at runtime.
79
Collection Interfacepublic interface Collection<E> extends
Iterable<E> { // Basic operations
int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional
80
Collection Interface (cont’d)
81
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
Return a iterator: an object for traversing through a
collection and to remove elements from the collection
selectively
General-purpose ImplementationsInterfaces
Implementations Hash table Resizable
array Tree Linked list Hash table + Linked list Set HashSet TreeSet LinkedHashSet List ArrayList LinkedList Queue Map HashMap TreeMap LinkedHashMap
82
Interface
Implementation
Hash table
Resizablearray
Tree Linkedlist
Hash table+Linked list
Set HashSet
TreeSet
LinkedHashSet
List ArrayList
LinkedList
Queue
Map HashMap
TreeMap
LinkedHashMap
Lists: ordered collectionList: ordered Collection that can
contain duplicatesImplemented via interface List
ArrayList, vectorArrayList behaves like Vector without
synchronization and therefore execute faster than Vectors (no overhead of thread synchronization)
LinkedLists can be used to create stacks, queues, trees and deques (double-ended queues, pronounced “decks”).
83
ArrayList and IteratorArrayList example
Demonstrate Collection interface capabilitiesPlace two String arrays in ArrayListsUse Iterator to remove elements in ArrayList
84
Outline 1 // Fig. 19.3: CollectionTest.java
2 // Using the Collection interface.
3 import java.util.List;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Iterator;
7
8 public class CollectionTest
9 {
10 private static final String[] colors =
11 { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };
12 private static final String[] removeColors =
13 { "RED", "WHITE", "BLUE" };
14
15 // create ArrayList, add Colors to it and manipulate it
16 public CollectionTest()
17 {
18 List< String > list = new ArrayList< String >();
19 List< String > removeList = new ArrayList< String >(); 20
85
Create ArrayList objects and assign their references to variable list and
removeList, respectively
Outline21 // add elements in colors array to list
22 for ( String color : colors )
23 list.add( color );
24
25 // add elements in removeColors to removeList
26 for ( String color : removeColors )
27 removeList.add( color );
28
29 System.out.println( "ArrayList: " );
30
31 // output list contents
32 for ( int count = 0; count < list.size(); count++ )
33 System.out.printf( "%s ", list.get( count ) );
34
35 // remove colors contained in removeList
36 removeColors( list, removeList );
37
38 System.out.println( "\n\nArrayList after calling removeColors: " );
39
40 // output list contents
41 for ( String color : list )
42 System.out.printf( "%s ", color );
43 } // end CollectionTest constructor 44
86
add objects to list and removeList, respectively
Get number of ArrayList elements
retrieve individual element values
Method removeColors takes two Collections as arguments; Line 36
passes two Lists, which extends Collection, to this method
Outline45 // remove colors specified in collection2 from collection1
46 private void removeColors(
47 Collection< String > collection1, Collection< String > collection2 )
48 {
49 // get iterator
50 Iterator< String > iterator = collection1.iterator();
51
52 // loop while collection has items
53 while ( iterator.hasNext() )
54
55 if ( collection2.contains( iterator.next() ) )
56 iterator.remove(); // remove current Color
57 } // end method removeColors
58
59 public static void main( String args[] )
60 {
61 new CollectionTest();
62 } // end main
63 } // end class CollectionTest
ArrayList: MAGENTA RED WHITE BLUE CYAN ArrayList after calling removeColors: MAGENTA CYAN
87
Take any Collections containing strings as arguments
hasNext determines whether the Iterator contains more elements
next returns a reference to the next element
contains determines whether collection2 contains the element returned by next
Use Iterator method remove to remove String from Iterator
Common Programming Error
If a collection is modified by one of its methods after an iterator is created for that collection, the iterator immediately becomes invalid—any operations performed with the iterator after this point throw ConcurrentModificationExceptions. For this reason, iterators are said to be “fail fast.”
88
LinkedListLinkedList example
Add elements of one List to the otherConvert Strings to uppercaseDelete a range of elements
89
Outline 1 // Fig. 19.4: ListTest.java
2 // Using LinkLists.
3 import java.util.List;
4 import java.util.LinkedList;
5 import java.util.ListIterator;
6
7 public class ListTest
8 {
9 private static final String colors[] = { "black", "yellow",
10 "green", "blue", "violet", "silver" };
11 private static final String colors2[] = { "gold", "white",
12 "brown", "blue", "gray", "silver" };
13
14 // set up and manipulate LinkedList objects
15 public ListTest()
16 {
17 List< String > list1 = new LinkedList< String >();
18 List< String > list2 = new LinkedList< String >();
19
20 // add elements to list link
21 for ( String color : colors )
22 list1.add( color ); 23
90
Create two LinkedList objects
Use List method add to append elements from array colors to the end of list1
Outline
24 // add elements to list link2
25 for ( String color : colors2 )
26 list2.add( color );
27
28 list1.addAll( list2 ); // concatenate lists
29 list2 = null; // release resources
30 printList( list1 ); // print list1 elements
31
32 convertToUppercaseStrings( list1 ); // convert to upper case string
33 printList( list1 ); // print list1 elements
34
35 System.out.print( "\nDeleting elements 4 to 6..." );
36 removeItems( list1, 4, 7 ); // remove items 4-7 from list
37 printList( list1 ); // print list1 elements
38 printReversedList( list1 ); // print list in reverse order
39 } // end ListTest constructor
40
41 // output List contents
42 public void printList( List< String > list )
43 {
44 System.out.println( "\nlist: " );
45
46 for ( String color : list )
47 System.out.printf( "%s ", color );
48
49 System.out.println();
50 } // end method printList 51
91
Use List method add to append elements from array colors2 to the end of list2
Use List method addAll to append all elements of list2 to the end of list1
Method printList allows any Lists containing strings to be
passed as arguments to this method
Outline52 // locate String objects and convert to uppercase
53 private void convertToUppercaseStrings( List< String > list )
54 {
55 ListIterator< String > iterator = list.listIterator();
56
57 while ( iterator.hasNext() )
58 {
59 String color = iterator.next(); // get item
60 iterator.set( color.toUpperCase() ); // convert to upper case
61 } // end while
62 } // end method convertToUppercaseStrings
63
64 // obtain sublist and use clear method to delete sublist items
65 private void removeItems( List< String > list, int start, int end )
66 {
67 list.subList( start, end ).clear(); // remove items
68 } // end method removeItems
69
70 // print reversed list
71 private void printReversedList( List< String > list )
72 {
73 ListIterator< String > iterator = list.listIterator( list.size() ); 74
92
any List that contains strings
subList: obtain a portion of the List
calllistIterator with one argument (starting position) to get a bidirectional iterator
Outline75 System.out.println( "\nReversed List:" );
76
77 // print list in reverse order
78 while ( iterator.hasPrevious() )
79 System.out.printf( "%s ", iterator.previous() );
80 } // end method printReversedList
81
82 public static void main( String args[] )
83 {
84 new ListTest();
85 } // end main
86 } // end class ListTest
list: black yellow green blue violet silver gold white brown blue gray silver list: BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER Deleting elements 4 to 6... list: BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER Reversed List: SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK
93
hasPrevious: determine whether there are more elements while traversing the list backward
Invoke ListIterator method previous to get the previous
element from the list
SetsSet interface: Collection that contains
unique elementsImplementations:
HashSetStores elements in hash table
TreeSetStores elements in tree
Example: using HashSet to find unique elements in a collection …
94
Outline 1 // Fig. 19.18: SetTest.java
2 // Using a HashSet to remove duplicates.
3 import java.util.List;
4 import java.util.Arrays;
5 import java.util.HashSet;
6 import java.util.Set;
7 import java.util.Collection;
8
9 public class SetTest
10 {
11 private static final String colors[] = { "red", "white", "blue",
12 "green", "gray", "orange", "tan", "white", "cyan",
13 "peach", "gray", "orange" };
14
15 // create and output ArrayList
16 public SetTest()
17 {
18 List< String > list = Arrays.asList( colors );
19 System.out.printf( "ArrayList: %s\n", list );
20 printNonDuplicates( list );
21 } // end SetTest constructor 22
95
Create a List that contains String objects
Outline23 // create set from array to eliminate duplicates
24 private void printNonDuplicates( Collection< String > collection )
25 {
26 // create a HashSet
27 Set< String > set = new HashSet< String >( collection );
28
29 System.out.println( "\nNonduplicates are: " );
30
31 for ( String s : set )
32 System.out.printf( "%s ", s );
33
34 System.out.println();
35 } // end method printNonDuplicates
36
37 public static void main( String args[] )
38 {
39 new SetTest();
40 } // end main
41 } // end class SetTest
ArrayList: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange] Nonduplicates are: red cyan white tan gray green orange blue peach
96
Method printNonDuplicates accepts a Collection of type String
Conversion construct: create a HashSet from Collection argument
Software Engineering ObservationCollection interface is used to pass around
collections of objects where maximum generality is desired. The collection might be a linked list, an array list, a
set , … E.g., All general-purpose collection implementations
have a conversion constructor that takes a Collection argument. It initializes new collection to contain all elements in specified collection
Next: useful Collection methods for manipulating any collections
97
How to iterate Collectionfor-each construct: to concisely traverse
a collection or array using a for loop. for (Object o : collection)
System.out.println(o); Using Iterator: an object for traversing
through a collection and to remove elements from the collection selectively, if desired.
Use Iterator instead of the for-each construct when you need to remove element.
98
Iterator 1. Get an Iterator for a collection by calling its
iterator method 2. Call methods of Iterator to traverse through
collectionIterator interface: public interface Iterator<E> {
boolean hasNext(); E next(); void remove(); //optional } hasNext: returns true if iteration has more elementsnext: returns next element in the iteration.
99
Iterator: remove method remove: removes last element that was
returned by next from underlying Collection. only safe way to modify a collection during
iterationmay be called only once per call to next and
throws an exception if this rule is violated. behavior is unspecified if underlying collection is
modified in any other way while iteration is in progress.
100
toArray methodtoArray: translate contents of a Collection into an array. a bridge between collections and older APIs that
expect arrays on inputObject[] toArray(); //creates a new array of
Object. <T> T[] toArray(T[] a); //allows caller to provide
an array or to choose runtime type of output array. E.g, to dump contents of a Collection c into a
newly allocated array of ObjectObject[] a = c.toArray(); E.g., suppose that c is known to contain only
string, to dumps contents of c into a newly allocated array of String:
String[] a = c.toArray(new String[0]); 101
Java Collection Framework: Interfaces
102
MapsMap interface: associates keys to values,
one-to-one mapping (no duplicate keys)Implementation classes
Hashtable, HashMap Store elements in hash tables
TreeMap Store elements in trees
Interface SortedMap Extends Map Maintains its keys in sorted order
103
hash tableHash tables: data structure that use
hashing, an algorithm for determining a key in tableEach table cell is a hash “bucket”, i.e., linked
list of all key-value pairs that hash to that cell (collision)
Load factor in a hash table: average length of bucket
104
Hash table
Outline 1 // Fig. 19.20: WordTypeCount.java
2 // Program counts the number of occurrences of each word in a string
3 import java.util.StringTokenizer;
4 import java.util.Map;
5 import java.util.HashMap;
6 import java.util.Set;
7 import java.util.TreeSet;
8 import java.util.Scanner;
9
10 public class WordTypeCount
11 {
12 private Map< String, Integer > map;
13 private Scanner scanner;
14
15 public WordTypeCount()
16 {
17 map = new HashMap< String, Integer >(); // create HashMap
18 scanner = new Scanner( System.in ); // create scanner
19 createMap(); // create map based on user input
20 displayMap(); // display map content
21 } // end WordTypeCount constructor 22
105
Create an empty HashMap with a default capacity 16 and a
default load factor 0.75. The keys are of type String and the
values are of type Integer
Outline23 // create map from user input
24 private void createMap()
25 {
26 System.out.println( "Enter a string:" ); // prompt for user input
27 String input = scanner.nextLine();
28
29 // create StringTokenizer for input
30 StringTokenizer tokenizer = new StringTokenizer( input );
31
32 // processing input text
33 while ( tokenizer.hasMoreTokens() ) // while more input
34 {
35 String word = tokenizer.nextToken().toLowerCase(); // get word
36
37 // if the map contains the word
38 if ( map.containsKey( word ) ) // is word in map
39 {
40 int count = map.get( word ); // get current count
41 map.put( word, count + 1 ); // increment count
42 } // end if
43 else
44 map.put( word, 1 ); // add new word with a count of 1 to map
45 } // end while
46 } // end method createMap
47
106
containsKey: whether a key specified as an argument is in hash table
Create a StringTokenizer to break input string into individual words
Use method get to obtain the key’s associated value in the map
Increment the value and use method put to replace the key’s associated value
Outline48 // display map content
49 private void displayMap()
50 {
51 Set< String > keys = map.keySet(); // get keys
52
53 // sort keys
54 TreeSet< String > sortedKeys = new TreeSet< String >( keys );
55
56 System.out.println( "Map contains:\nKey\t\tValue" );
57
58 // generate output for each key in map
59 for ( String key : sortedKeys )
60 System.out.printf( "%-10s%10s\n", key, map.get( key ) );
61
62 System.out.printf(
63 "\nsize:%d\nisEmpty:%b\n", map.size(), map.isEmpty() );
64 } // end method displayMap 65
107
Use HashMap method keySet to obtain a set of the keys
Access each key and its value in the map
Call Map method size to get the number of key-value pairs in the Map
Call Map method isEmpty to determine whether the Map is empty
Outline66 public static void main( String args[] )
67 {
68 new WordTypeCount();
69 } // end main
70 } // end class WordTypeCount
Enter a string: To be or not to be: that is the question Whether 'tis nobler to suffer Map contains: Key Value 'tis 1 be 1 be: 1 is 1 nobler 1 not 1 or 1 question 1 suffer 1 that 1 the 1 to 3 whether 1 size:13 isEmpty:false
108
Collections algorithms
Algorithm Description
sort Sorts the elements of a List.
binarySearch Locates an object in a List.
reverse Reverses the elements of a List.
shuffle Randomly orders a List’s elements.
fill Sets every List element to refer to a specified object.
Copy Copies references from one List into another.
min Returns the smallest element in a Collection.
max Returns the largest element in a Collection.
addAll Appends all elements in an array to a collection.
frequency Calculates how many elements in the collection are equal to the specified element.
disjoint Determines whether two collections have no elements in common. 109
Collections framework provides set of algorithms, implemented as static methods of Collections class
Software Engineering ObservationCollections framework algorithms are
polymorphic methodfirst argument is the collection on which the
operation is to be performed. majority of the algorithms operate on List instances, a few operate on arbitrary Collection instances.
Each algorithm can operate on objects that implement specific interfaces, regardless of the underlying implementations.
110
Algorithm sortsort
Sorts List elementsOrder is determined by natural order of elements’ typeList elements must implement the Comparable interfaceOr, pass a Comparator to method sort
Sorting in ascending orderCollections method sort
Sorting in descending orderCollections static method reverseOrder
Sorting with a ComparatorCreate a custom Comparator class
111
Exampleimport java.util.*; public class Sort { public static void main(String[] args) { List<String> list =
Arrays.asList(args); Collections.sort(list); System.out.println(list); } }
112
Outline 1 // Fig. 19.8: Sort1.java
2 // Using algorithm sort.
3 import java.util.List;
4 import java.util.Arrays;
5 import java.util.Collections;
6
7 public class Sort1
8 {
9 private static final String suits[] =
10 { "Hearts", "Diamonds", "Clubs", "Spades" };
11
12 // display array elements
13 public void printElements()
14 {
15 List< String > list = Arrays.asList( suits ); // create List 16
113
Create List of Strings
Outline17 // output list
18 System.out.printf( "Unsorted array elements:\n%s\n", list );
19
20 Collections.sort( list ); // sort ArrayList
21
22 // output list
23 System.out.printf( "Sorted array elements:\n%s\n", list );
24 } // end method printElements
25
26 public static void main( String args[] )
27 {
28 Sort1 sort1 = new Sort1();
29 sort1.printElements();
30 } // end main
31 } // end class Sort1
Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted array elements: [Clubs, Diamonds, Hearts, Spades]
114
Implicit call to the list’s toString method to output the list contents
Use algorithm sort to order the elements of list in ascending order
Outline 1 // Fig. 19.9: Sort2.java
2 // Using a Comparator object with algorithm sort.
3 import java.util.List;
4 import java.util.Arrays;
5 import java.util.Collections;
6
7 public class Sort2
8 {
9 private static final String suits[] =
10 { "Hearts", "Diamonds", "Clubs", "Spades" };
11
12 // output List elements
13 public void printElements()
14 {
15 List list = Arrays.asList( suits ); // create List 16
115
Outline17 // output List elements
18 System.out.printf( "Unsorted array elements:\n%s\n", list );
19
20 // sort in descending order using a comparator
21 Collections.sort( list, Collections.reverseOrder() );
22
23 // output List elements
24 System.out.printf( "Sorted list elements:\n%s\n", list );
25 } // end method printElements
26
27 public static void main( String args[] )
28 {
29 Sort2 sort2 = new Sort2();
30 sort2.printElements();
31 } // end main
32 } // end class Sort2
Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted list elements: [Spades, Hearts, Diamonds, Clubs]
116
Method reverseOrder of class Collections returns a
Comparator object that represents the collection’s reverse order
Method sort of class Collections can use a Comparator object to sort a List
Outline 1 // Fig. 19.10: TimeComparator.java
2 // Custom Comparator class that compares two Time2 objects.
3 import java.util.Comparator;
4
5 public class TimeComparator implements Comparator< Time2 >
6 {
7 public int compare( Time2 tim1, Time2 time2 )
8 {
9 int hourCompare = time1.getHour() - time2.getHour(); // compare hour
10
11 // test the hour first
12 if ( hourCompare != 0 )
13 return hourCompare;
14
15 int minuteCompare =
16 time1.getMinute() - time2.getMinute(); // compare minute
17
18 // then test the minute
19 if ( minuteCompare != 0 )
20 return minuteCompare;
21
22 int secondCompare =
23 time1.getSecond() - time2.getSecond(); // compare second
24
25 return secondCompare; // return result of comparing seconds
26 } // end method compare
27 } // end class TimeComparator
117
Custom comparator TimeComparator implements Comparator interface and
compares Time2 object
Implement method compare to determine the order of two Time2 objects
Outline 1 // Fig. 19.11: Sort3.java
2 // Sort a list using the custom Comparator class TimeComparator.
3 import java.util.List;
4 import java.util.ArrayList;
5 import java.util.Collections;
6
7 public class Sort3
8 {
9 public void printElements()
10 {
11 List< Time2 > list = new ArrayList< Time2 >(); // create List
12
13 list.add( new Time2( 6, 24, 34 ) );
14 list.add( new Time2( 18, 14, 58 ) );
15 list.add( new Time2( 6, 05, 34 ) );
16 list.add( new Time2( 12, 14, 58 ) );
17 list.add( new Time2( 6, 24, 22 ) ); 18
118
Outline19 // output List elements
20 System.out.printf( "Unsorted array elements:\n%s\n", list );
21
22 // sort in order using a comparator
23 Collections.sort( list, new TimeComparator() );
24
25 // output List elements
26 System.out.printf( "Sorted list elements:\n%s\n", list );
27 } // end method printElements
28
29 public static void main( String args[] )
30 {
31 Sort3 sort3 = new Sort3();
32 sort3.printElements();
33 } // end main
34 } // end class Sort3
Unsorted array elements: [6:24:34 AM, 6:14:58 PM, 6:05:34 AM, 12:14:58 PM, 6:24:22 AM] Sorted list elements: [6:05:34 AM, 6:24:22 AM, 6:24:34 AM, 12:14:58 PM, 6:14:58 PM]
119
Sort in order using a custom comparator TimeComparator
Algorithms on Listreverse: Reverses the order of List
elementsfill: populates List elements with
valuescopy: Creates copy of a Listmax: Returns largest element in Listmin: Returns smallest element in ListbinarySearch: Locates object in List
120
Outline 1 // Fig. 19.13: Algorithms1.java
2 // Using algorithms reverse, fill, copy, min and max.
3 import java.util.List;
4 import java.util.Arrays;
5 import java.util.Collections;
6
7 public class Algorithms1
8 {
9 private Character[] letters = { ‘P’, ‘C’, ‘M’ };
10 private Character[] lettersCopy;
11 private List< Character > list;
12 private List< Character > copyList;
13
14 // create a List and manipulate it with methods from Collections
15 public Algorithms1()
16 {
17 list = Arrays.asList( letters ); // get List
18 lettersCopy = new Character[ 3 ];
19 copyList = Arrays.asList( lettersCopy ); // list view of lettersCopy
20
21 System.out.println( "Initial list: " );
22 output( list );
23
24 Collections.reverse( list ); // reverse order
25 System.out.println( "\nAfter calling reverse: " );
26 output( list ); 27
121
Use method reverse of class Collections to
obtain List in reverse order
Outline28 Collections.copy( copyList, list ); // copy List
29 System.out.println( "\nAfter copying: " );
30 output( copyList );
31
32 Collections.fill( list, ‘R’ ); // fill list with Rs
33 System.out.println( "\nAfter calling fill: " );
34 output( list );
35 } // end Algorithms1 constructor
36
37 // output List information
38 private void output( List< Character > listRef )
39 {
40 System.out.print( "The list is: " );
41
42 for ( Character element : listRef )
43 System.out.printf( "%s ", element );
44
45 System.out.printf( "\nMax: %s", Collections.max( listRef ) );
46 System.out.printf( " Min: %s\n", Collections.min( listRef ) );
47 } // end method output
48
122
Use method copy of class Collections to obtain copy of List
Use method fill of class Collections to populate List with the letter ‘R’
Obtain minimum value in List
Outline49 public static void main( String args[] )
50 {
51 new Algorithms1();
52 } // end main
53 } // end class Algorithms1
Initial list: The list is: P C M Max: P Min: C After calling reverse: The list is: M C P Max: P Min: C After copying: The list is: M C P Max: P Min: C After calling fill: The list is: R R R Max: R Min: R
123
Algorithm binarySearchbinarySearch locates object in List
Returns index of object in List if object exists
Returns negative value if Object does not existCalculate insertion point: if the object is to
be inserted into the List, where should it be inserted ?
Make the insertion point sign negativeSubtract 1 from insertion point (Why ?)
124
Outline 1 // Fig. 19.14: BinarySearchTest.java
2 // Using algorithm binarySearch.
3 import java.util.List;
4 import java.util.Arrays;
5 import java.util.Collections;
6 import java.util.ArrayList;
7
8 public class BinarySearchTest
9 {
10 private static final String colors[] = { "red", "white",
11 "blue", "black", "yellow", "purple", "tan", "pink" };
12 private List< String > list; // ArrayList reference
13
14 // create, sort and output list
15 public BinarySearchTest()
16 {
17 list = new ArrayList< String >( Arrays.asList( colors ) );
18 Collections.sort( list ); // sort the ArrayList
19 System.out.printf( "Sorted ArrayList: %s\n", list );
20 } // end BinarySearchTest constructor
21
125
Sort List in ascending order
Outline22 // search list for various values
23 private void search()
24 {
25 printSearchResults( colors[ 3 ] ); // first item
26 printSearchResults( colors[ 0 ] ); // middle item
27 printSearchResults( colors[ 7 ] ); // last item
28 printSearchResults( "aqua" ); // below lowest
29 printSearchResults( "gray" ); // does not exist
30 printSearchResults( "teal" ); // does not exist
31 } // end method search
32
33 // perform searches and display search result
34 private void printSearchResults( String key )
35 {
36 int result = 0;
37
38 System.out.printf( "\nSearching for: %s\n", key );
39 result = Collections.binarySearch( list, key );
40
41 if ( result >= 0 )
42 System.out.printf( "Found at index %d\n", result );
43 else
44 System.out.printf( "Not Found (%d)\n",result );
45 } // end method printSearchResults 46
126
Use method binarySearch of class Collections to
search list for specified key
Outline47 public static void main( String args[] )
48 {
49 BinarySearchTest binarySearchTest = new BinarySearchTest();
50 binarySearchTest.search();
51 } // end main
52 } // end class BinarySearchTest
Sorted ArrayList: [black, blue, pink, purple, red, tan, white, yellow] Searching for: black Found at index 0 Searching for: red Found at index 4 Searching for: pink Found at index 2 Searching for: aqua Not Found (-1) Searching for: gray Not Found (-3) Searching for: teal Not Found (-7)
127
Algorithms addAll, frequency and disjointaddAll
Insert all elements of an array into a collection
frequencyCalculate the number of times a specific
element appear in the collectionDisjoint
Determine whether two collections have elements in common
128
Outline 1 // Fig. 19.15: Algorithms2.java
2 // Using algorithms addAll, frequency and disjoint.
3 import java.util.List;
4 import java.util.Vector;
5 import java.util.Arrays;
6 import java.util.Collections;
7
8 public class Algorithms2
9 {
10 private String[] colors = { "red", "white", "yellow", "blue" };
11 private List< String > list;
12 private Vector< String > vector = new Vector< String >();
13
14 // create List and Vector
15 // and manipulate them with methods from Collections
16 public Algorithms2()
17 {
18 // initialize list and vector
19 list = Arrays.asList( colors );
20 vector.add( "black" );
21 vector.add( "red" );
22 vector.add( "green" );
23
24 System.out.println( "Before addAll, vector contains: " ); 25
129
Outline26 // display elements in vector
27 for ( String s : vector )
28 System.out.printf( "%s ", s );
29
30 // add elements in colors to list
31 Collections.addAll( vector, colors );
32
33 System.out.println( "\n\nAfter addAll, vector contains: " );
34
35 // display elements in vector
36 for ( String s : vector )
37 System.out.printf( "%s ", s );
38
39 // get frequency of "red"
40 int frequency = Collections.frequency( vector, "red" );
41 System.out.printf(
42 "\n\nFrequency of red in vector: %d\n", frequency ); 43
130
Invoke method addAll to add elements in array colors to vector
Get the frequency of String “red” in Collection vector
using method frequency
Outline44 // check whether list and vector have elements in common 45 boolean disjoint = Collections.disjoint( list, vector );
46
47 System.out.printf( "\nlist and vector %s elements in common\n",
48 ( disjoint ? "do not have" : "have" ) );
49 } // end Algorithms2 constructor
50
51 public static void main( String args[] )
52 {
53 new Algorithms2();
54 } // end main
55 } // end class Algorithms2
Before addAll, vector contains: black red green After addAll, vector contains: black red green red white yellow blue Frequency of red in vector: 2 list and vector have elements in common
131
Invoke method disjoint to test whether Collections list and vector have elements in common
Synchronized CollectionsBuilt-in collections are unsynchronized
Concurrent access to a Collection can cause errors
Java provides synchronization wrappers to avoid thisVia set of public static methods
132
public static method headers
< T > Collection< T > synchronizedCollection( Collection< T > c )
< T > List< T > synchronizedList( List< T > aList )
< T > Set< T > synchronizedSet( Set< T > s )
< T > SortedSet< T > synchronizedSortedSet( SortedSet< T > s )
< K, V > Map< K, V > synchronizedMap( Map< K, V > m )
< K, V > SortedMap< K, V > synchronizedSortedMap( SortedMap< K, V > m )
Unmodifiable CollectionsUnmodifiable wrapper
Converting collections to unmodifiable collections
Throw UnsorrtedOperationException if attempts are made to modify the collection
133
public static method headers
< T > Collection< T > unmodifiableCollection( Collection< T > c )
< T > List< T > unmodifiableList( List< T > aList )
< T > Set< T > unmodifiableSet( Set< T > s )
< T > SortedSet< T > unmodifiableSortedSet( SortedSet< T > s )
< K, V > Map< K, V > unmodifiableMap( Map< K, V > m )
< K, V > SortedMap< K, V > unmodifiableSortedMap( SortedMap< K, V > m )