Transcript Outline

Chapter 21 – Java Utilities Package and
Bit Manipulation
Outline
21.1
21.2
21.3
21.4
21.5
Introduction
Vector Class and Enumeration Interface
Stack Class of Package java.util
Hashtable Class
Properties Class
21.6, 21.7 Bit Manipulation Skipped
 2003 Prentice Hall, Inc. All rights reserved.
1
2
21.1 Introduction
• Utility classes and interfaces
– Contained in package java.util
•
•
•
•
•
•
Class Vector
Interface Enumeration
Class Stack
Class Hashtable
Class Properties
Class BitSet
 2003 Prentice Hall, Inc. All rights reserved.
21.2 Vector Class and Enumeration
Interface
• Class java.util.Vector
– Array-like data structures that can resize themselves
dynamically
– Contains a capacity
– Grows by capacity increment if it requires additional space
– Three constructors
• Vector( ): with initial capacity of 10 elements and
capacity increment of 0, meaning double in size for each
growing
• Vector(int initialCapacity)
• Vector(int initialCapacity, int
capacityIncreent)
• Vector(Collection c): creates a copy of c’s elements
and stores them in the Vector
 2003 Prentice Hall, Inc. All rights reserved.
3
21.2 Vector Class and Enumeration
Interface
• Class java.util.Vector
– Methods
• add(Object element): Adds an element to the end of the Vector
(shifting)
• add(int index, object element): Inserts the specified
element at the specified position in this Vector (shifting)
• set(int index, Object element) : Replaces the element at the
specified position in this Vector with the specified element.
• inserElementAt(Object obj, int index) : Inserts the specified object as a
component in this vector at the specified index. (shifting)
• firstElement( ), lastElement( )
• remove(Object o), remove(int index): (shifting)
• Elements( ): Returns an enumeration of the components of this vector.
• Class java.util.Enumeration
– hasMoreElements( )
– nextElement( )
 2003 Prentice Hall, Inc. All rights reserved.
4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
// Fig. 21.1: VectorTest.java
// Using the Vector class.
import java.util.*;
public class VectorTest {
private static final String colors[] = { "red", "white", "blue" };
public VectorTest()
{
Vector vector = new Vector();
printVector( vector ); // print vector
Line 10
17 and 19
Create VectorLines
with14,
initial
capacity of 10 elements and
Line of
24 zero
capacity increment
// add elements to the vector
vector.add( "magenta" );
Line 25
for ( int count = 0; count < colors.length; count++ )
vector.add( colors[ count ] );
vector.add( "cyan" );
printVector( vector ); // print vector
VectorTest.java
Call Vector method add to add
objects to the end of the Vector
Call Vector method firstElement to return
Calla Vector
lastElement
return
reference method
to the first
element in thetoVector
a reference to the last element in the Vector
// output the first and last elements
try {
System.out.println( "First element: " + vector.firstElement() );
System.out.println( "Last element: " + vector.lastElement() );
}
 2003 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Outline
// catch exception if vector is empty Vector method contains returns
that indicates whether
catch ( NoSuchElementException exceptionboolean
) {
exception.printStackTrace();
Vector contains a specific Object
VectorTest.java
}
Line 34
// does vector contain "red"?
if ( vector.contains( "red" ) )
System.out.println( "\n\"red\" found at index " +
Line 36
vector.indexOf( "red" ) + "\n" );
Vector method remove removes the first
else
occurrence of its argument Object fromLine
Vector
40
System.out.println( "\n\"red\" not found\n" );
Vector method indexOf
vector.remove( "red" ); // remove the
stringindex
"red"of first location in
returns
System.out.println( "\"red\" has been removed" );
Vector containing the argument
Lines 52-53
printVector( vector ); // print vector
// does vector contain "red" after remove operation?
if ( vector.contains( "red" ) )
System.out.println( "\"red\" found at index " +
vector.indexOf( "red" ) );
else
System.out.println( "\"red\" not found" );
// print the size and capacity of vector
System.out.println( "\nSize: " + vector.size() +
"\nCapacity: " + vector.capacity() );
} // end constructor
Vector methods size and
capacity return number of
elements in Vector and
Vector capacity, respectively
 2003 Prentice Hall, Inc.
All rights reserved.
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
private void printVector( Vector vectorToOutput )
Vector method isEmpty
{
if ( vectorToOutput.isEmpty() )
returns true if there are no
System.out.print( "vector is empty" ); // vectorToOutput
is Vector
empty
elements in the
else { // iterate through the elements
System.out.print( "vector contains: " );
Enumeration items = vectorToOutput.elements();
while ( items.hasMoreElements() )
System.out.print( items.nextElement() + " " );
Outline
VectorTest.java
Line 59
Vector method elements
Line 64
returns Enumeration
for
iterating Vector elements
}
System.out.println( "\n" );
}
public static void main( String args[] )
{
new VectorTest(); // create object and call its constructor
}
} // end class VectorTest
 2003 Prentice Hall, Inc.
All rights reserved.
vector is empty
Outline
vector contains: magenta red white blue cyan
First element: magenta
Last element: cyan
VectorTest.java
"red" found at index 1
"red" has been removed
vector contains: magenta white blue cyan
"red" not found
Size: 4
Capacity: 10
 2003 Prentice Hall, Inc.
All rights reserved.
9
21.3 Stack Class of Package java.util
• Stack
– Implements stack data structure
– Extends class Vector
– Stores references to Objects (as does Vector)
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
// Fig. 21.2: StackTest.java
// Program to test java.util.Stack.
import java.util.*;
StackTest.java
public class StackTest {
Line 9
public StackTest()
{
Stack stack = new Stack();
Create empty
Stack
Lines
18, 20, 22 and
// create objects to store in the stack
Boolean bool = Boolean.TRUE;
Character character = new Character( '$' );
Integer integer = new Integer( 34567 );
String string = "hello";
// use push
stack.push(
printStack(
stack.push(
printStack(
stack.push(
printStack(
stack.push(
printStack(
method
bool );
stack );
character );
stack );
integer );
stack );
string );
stack );
24
Stack method push adds
Object to top of Stack
 2003 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// remove items from stack
try {
Object removedObject = null;
Outline
Stack method pop removes
Object from top of Stack
while ( true ) {
removedObject = stack.pop(); // use pop method
System.out.println( removedObject.toString() + " popped" );
printStack( stack );
}
StackTest.java
Line 32
Line 46
}
// catch exception if stack is empty when item popped
catch ( EmptyStackException emptyStackException ) {
emptyStackException.printStackTrace();
}
}
Line 51
Stack method isEmpty returns
true if Stack is empty
private void printStack( Stack stack )
{
if ( stack.isEmpty() )
System.out.print( "stack is empty" ); // the stack is empty
else {
System.out.print( "stack contains: " );
Enumeration items = stack.elements();
Stack extends Vector, so
class Stack may use method
elements to obtain
Enumeration for Stack
 2003 Prentice Hall, Inc.
All rights reserved.
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// iterate through the elements
while ( items.hasMoreElements() )
System.out.print( items.nextElement() + " " );
}
Outline
StackTest.java
System.out.println( "\n" ); // go to the next line
}
public static void main( String args[] )
{
new StackTest();
}
} // end class StackTest
 2003 Prentice Hall, Inc.
All rights reserved.
stack contains: true
stack contains: true $
Outline
StackTest.java
stack contains: true $ 34567
stack contains: true $ 34567 hello
hello popped
stack contains: true $ 34567
34567 popped
stack contains: true $
$ popped
stack contains: true
true popped
stack is empty
java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:79)
at java.util.Stack.pop(Stack.java:61)
at StackTest.<init>(StackTest.java:32)
at StackTest.main(StackTest.java:63)
 2003 Prentice Hall, Inc.
All rights reserved.
14
21.4 Hashtable Class
• Hashtable
–
–
Similar to array, useful for keys not positive integers or keys
sparsely spread over a huge range
Data structure that uses hashing
•
–
Algorithm for determining a key in table
– Keys in tables have associated values (data)
When collisions occur
1. hash again with another hashing transformation
2. Each table cell is a hash “bucket”
• Linked list of all key-value pairs that hash to that cell
• Minimizes collisions
• Chosen in JAVA
–
Methods
•
get, put, keys, size, isempty
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 21.3: WordTypeCount.java
// Count the number of occurrences of each word in a string.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class WordTypeCount extends JFrame {
private JTextArea inputField;
private JLabel prompt;
private JTextArea display;
private JButton goButton;
Outline
WordTypeCount.j
ava
Line 21
private Hashtable table;
public WordTypeCount()
{
super( "Word Type Count" );
inputField = new JTextArea( 3, 20 );
table = new Hashtable();
Create empty Hashtable
goButton = new JButton( "Go" );
goButton.addActionListener(
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent event )
{
createTable();
display.setText( createOutput() );
}
}
Outline
WordTypeCount.j
ava
// end anonymous inner class
); // end call to addActionListener
prompt = new JLabel( "Enter a string:" );
display = new JTextArea( 15, 20 );
display.setEditable( false );
JScrollPane displayScrollPane = new JScrollPane( display );
// add components to GUI
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( prompt );
container.add( inputField );
container.add( goButton );
container.add( displayScrollPane );
 2003 Prentice Hall, Inc.
All rights reserved.
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
setSize( 400, 400 );
setVisible( true );
} // end constructor
method
// create table from userHashtable
input
private void createTable()
{
containsKey
determines
String input = inputField.getText();
method get obtains
whether the keyHashtable
specified as an
StringTokenizer words = new StringTokenizer(
input,
" \n\t\r"
);
Object associated with
key from
Outline
WordTypeCount.j
ava
Line 66
argument is in the hash table
Line 68
Hashtable (returns null if
while ( words.hasMoreTokens() ) {
Hashtable method put adds
neither key nor Object
exist)
String word = words.nextToken().toLowerCase();
// get word
key and valueLines
to Hashtable
71 and 74
(returns
null
if
key
has been
// if the table contains the word
inserted previously)
if ( table.containsKey( word ) ) {
Integer count = (Integer) table.get( word ); // get value
// and increment it
table.put( word, new Integer( count.intValue() + 1 ) );
}
else // otherwise add the word with a value of 1
table.put( word, new Integer( 1 ) );
} // end while
 2003 Prentice Hall, Inc.
All rights reserved.
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
} // end method createTable
// create string containing table values
private String createOutput() {
String output = "";
Enumeration keys = table.keys();
Outline
WordTypeCount.j
ava
Line 83
Hashtable method keys returns an
returns
Enumeration of keys inLine
the hash
93 table
Hashtable
method
isEmpty returns
the number
of key-value
pairs
that indicates whether
the key-value pairs
in boolean
the hash table
Line 94
currentKey + "\t" Hashtable
+ table.get( currentKey
) +
"\n";
contains any
Objects
// iterate through the keys
while ( keys.hasMoreElements() ) {
Hashtable method size
Object currentKey = keys.nextElement();
// output
output +=
}
output += "size: " + table.size() + "\n";
output += "isEmpty: " + table.isEmpty() + "\n";
return output;
} // end method createOutput
 2003 Prentice Hall, Inc.
All rights reserved.
100
101
102
103
104
105
106
public static void main( String args[] )
{
WordTypeCount application = new WordTypeCount();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Outline
WordTypeCount.j
ava
} // end class WordTypeCount
 2003 Prentice Hall, Inc.
All rights reserved.
20
21.5 Properties Class
• Properties
– Persistent Hashtable
• Can be written to output stream
• Can be read from input stream
– Provides methods setProperty and getProperty
• Store/obtain key-value pairs of Strings
– Provides methods store, load to save to and load from
an OutputStream
• Preferences API (appears in 1.4)
– Replace Properties
– More robust mechanism
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 21.4: PropertiesTest.java
// Demonstrates class Properties of the java.util package.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class PropertiesTest extends JFrame {
private JLabel statusLabel;
private Properties table;
private JTextArea displayArea;
private JTextField valueField, nameField;
Outline
PropertiesTest.
java
Line 20
// set up GUI to test Properties table
public PropertiesTest()
{
super( "Properties Test" );
table = new Properties(); // create Properties table
Create empty Properties
Container container = getContentPane();
// set up NORTH of window's BorderLayout
JPanel northSubPanel = new JPanel();
northSubPanel.add( new JLabel( "Property value" ) );
valueField = new JTextField( 10 );
northSubPanel.add( valueField );
 2003 Prentice Hall, Inc.
All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
northSubPanel.add( new JLabel( "Property name (key)" ) );
nameField = new JTextField( 10 );
northSubPanel.add( nameField );
JPanel northPanel = new JPanel();
northPanel.setLayout( new BorderLayout() );
northPanel.add( northSubPanel, BorderLayout.NORTH );
Outline
PropertiesTest.
java
statusLabel = new JLabel();
northPanel.add( statusLabel, BorderLayout.SOUTH );
container.add( northPanel, BorderLayout.NORTH );
// set up CENTER of window's BorderLayout
displayArea = new JTextArea( 4, 35 );
container.add( new JScrollPane( displayArea ),
BorderLayout.CENTER );
// set up SOUTH of window's BorderLayout
JPanel southPanel = new JPanel();
southPanel.setLayout( new GridLayout( 1, 5 ) );
// button to put a name-value pair in Properties table
JButton putButton = new JButton( "Put" );
southPanel.add( putButton );
putButton.addActionListener(
 2003 Prentice Hall, Inc.
All rights reserved.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
new ActionListener() { // anonymous inner class
Outline
// put name-value pair in Properties table
Properties method
public void actionPerformed( ActionEvent event )
PropertiesTest.
setProperty stores
{
Object value = table.setProperty(
value for the specifiedjava
key
nameField.getText(), valueField.getText() );
Lines 64-65
if ( value == null )
showstatus( "Put: " + nameField.getText() +
" " + valueField.getText() );
else
showstatus( "Put: " + nameField.getText() + " " +
valueField.getText() + "; Replaced: " + value );
listProperties();
}
} // end anonymous inner class
); // end call to addActionListener
// button to empty contents of Properties table
JButton clearButton = new JButton( "Clear" );
southPanel.add( clearButton );
clearButton.addActionListener(
 2003 Prentice Hall, Inc.
All rights reserved.
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
Outline
new ActionListener() { // anonymous inner class
// use method clear to empty table
public void actionPerformed( ActionEvent event )
{
table.clear();
showstatus( "Table in memory cleared" );
listProperties();
}
PropertiesTest.
java
Lines 113-114
} // end anonymous inner class
); // end call to addActionListener
// button to get value of a property
JButton getPropertyButton = new JButton( "Get property" );
southPanel.add( getPropertyButton );
getPropertyButton.addActionListener(
new ActionListener() { // anonymous inner class
// use method getProperty to obtain a property value
public void actionPerformed( ActionEvent event )
{
Object value = table.getProperty(
nameField.getText() );
Properties method
getProperty locates value
associated with the specified key
if ( value != null )
showstatus( "Get property: " + nameField.getText() +
" " + value.toString() );
 2003 Prentice Hall, Inc.
All rights reserved.
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
else
showstatus( "Get: " + nameField.getText() +
" not in table" );
listProperties();
Outline
PropertiesTest.
java
}
} // end anonymous inner class
); // end call to addActionListener
// button to save contents of Properties table to file
JButton saveButton = new JButton( "Save" );
southPanel.add( saveButton );
saveButton.addActionListener(
new ActionListener() { // anonymous inner class
// use method save to place contents in file
public void actionPerformed( ActionEvent event )
{
// save contents of table
try {
FileOutputStream output =
new FileOutputStream( "props.dat" );
 2003 Prentice Hall, Inc.
All rights reserved.
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
table.store( output, "Sample Properties" );
output.close();
listProperties();
}
Outline
Properties method store
saves Properties contents
PropertiesTest.
to FileOutputStream
java
// process problems with file output
catch( IOException ioException ) {
ioException.printStackTrace();
}
Line 147
}
} // end anonymous inner class
); // end call to addActionListener
// button to load contents of Properties table from file
JButton loadButton = new JButton( "Load" );
southPanel.add( loadButton );
loadButton.addActionListener(
new ActionListener() { // anonymous inner class
// use method load to read contents from file
public void actionPerformed( ActionEvent event )
{
 2003 Prentice Hall, Inc.
All rights reserved.
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// load contents of table
try {
FileInputStream input =
new FileInputStream( "props.dat" );
table.load( input );
input.close();
listProperties();
}
Outline
PropertiesTest.
java
Properties method
load
Line 179
restores Properties contents
from FileInputStream
// process problems with file input
catch( IOException ioException ) {
ioException.printStackTrace();
}
}
} // end anonymous inner class
); // end call to addActionListener
container.add( southPanel, BorderLayout.SOUTH );
setSize( 550, 225 );
setVisible( true );
} // end constructor
 2003 Prentice Hall, Inc.
All rights reserved.
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// output property values
public void listProperties()
{
StringBuffer buffer = new StringBuffer();
String name, value;
Outline
Enumeration enumeration = table.propertyNames();
while ( enumeration.hasMoreElements() ) {
name = enumeration.nextElement().toString();
value = table.getProperty( name );
buffer.append( name ).append( '\t' );
buffer.append( value ).append( '\n' );
}
PropertiesTest.
java
Line 207
Properties method
propertyNames obtains
Enumeration of property names
displayArea.setText( buffer.toString() );
}
// display String in statusLabel label
public void showstatus( String s )
{
statusLabel.setText( s );
}
public static void main( String args[] )
{
PropertiesTest application = new PropertiesTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class PropertiesTest
 2003 Prentice Hall, Inc.
All rights reserved.
Outline
PropertiesTest.
java
Program Output
 2003 Prentice Hall, Inc.
All rights reserved.