Вы находитесь на странице: 1из 56

Chapter 21 Java Utilities Package and

Bit Manipulation
Outline

21.1
21.2
21.3
21.4
21.5
21.6
21.7

Introduction
Vector Class and Enumeration Interface
Stack Class of Package java.util
Hashtable Class
Properties Class
Bit Manipulation and the Bitwise Operators
BitSet Class

2003 Prentice Hall, Inc. All rights reserved.

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

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.1: VectorTest.java


// Using the Vector class.
import java.util.*;

VectorTest.java

public class VectorTest {


private static final String colors[] = { "red", "white", "blue" };

Line 10
Create Vector with initial
Lines 14,and
17 and 19
capacity of 10 elements
capacity increment of zero
Line 24

public VectorTest()
{
Vector vector = new Vector();
printVector( vector ); // print vector
// add elements to the vector
vector.add( "magenta" );
for ( int count = 0; count < colors.length; count++ )
vector.add( colors[ count ] );
vector.add( "cyan" );
printVector( vector ); // print vector

Line 25
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
Vector
method
contains
returns
// catch exception if vector is empty
that indicates whether
catch ( NoSuchElementException exception boolean
) {
exception.printStackTrace();
Vector contains a specific Object
VectorTest.java

// does vector contain "red"?


Line 34
if ( vector.contains( "red" ) )
System.out.println( "\n\"red\" found at index " +
vector.indexOf( "red" ) + "\n" );
Line
36
Vector method remove removes the
first
else
occurrence of its argument Object from Vector
System.out.println( "\n\"red\" not found\n" );

Line 40

Vector method indexOf


vector.remove( "red" ); // remove thereturns
stringindex
"red"of first location in
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

Outline

else { // iterate through the elements


System.out.print( "vector contains: " );
Enumeration items = vectorToOutput.elements();
while ( items.hasMoreElements() )
System.out.print( items.nextElement() + " " );

VectorTest.java

Line 59elements
Vector method
returns Enumeration for
Line 64 elements
iterating Vector

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

Outline

vector is empty

vector contains: magenta red white blue cyan

First element: magenta


Last element: cyan

"red" found at index 1

"red" has been removed


vector contains: magenta white blue cyan

"red" not found

Size: 4
Capacity: 10

VectorTest.java

2003 Prentice Hall, Inc.


All rights reserved.

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

Create empty
Stack
Lines
18, 20, 22 and
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;

Stack method pop removes


Object from top of Stack

Outline
StackTest.java

while ( true ) {
removedObject = stack.pop(); // use pop method
System.out.println( removedObject.toString() + " popped" );
printStack( stack );
}
}

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

Outline

// iterate through the elements


while ( items.hasMoreElements() )
System.out.print( items.nextElement() + " " );
}

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.

Outline

stack contains: true

stack contains: true $

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)

StackTest.java

2003 Prentice Hall, Inc.


All rights reserved.

21.4 Hashtable Class


Hashtable
Data structure that uses hashing
Algorithm for determining a key in table
Keys in tables have associated values (data)

Each table cell is a hash bucket

Linked list of all key-value pairs that hash to that cell


Minimizes collisions

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

Outline

// 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.*;

WordTypeCount.j
ava
Line 21

public class WordTypeCount extends JFrame {


private JTextArea inputField;
private JLabel prompt;
private JTextArea display;
private JButton goButton;
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

Outline

new ActionListener() { // anonymous inner class


public void actionPerformed( ActionEvent event )
{
createTable();
display.setText( createOutput() );
}
}

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

Outline

setSize( 400, 400 );


setVisible( true );
} // end constructor

method
// create table from user Hashtable
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

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

Outline

} // end method createTable


// create string containing table values
private String createOutput() {
String output = "";
Enumeration keys = table.keys();

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
) +Objects
"\n";
contains any

// 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

Outline

public static void main( String args[] )


{
WordTypeCount application = new WordTypeCount();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

WordTypeCount.j
ava

} // end class WordTypeCount

2003 Prentice Hall, Inc.


All rights reserved.

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

Preferences API

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

Outline

// 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.*;

PropertiesTest.
java
Line 20

public class PropertiesTest extends JFrame {


private JLabel statusLabel;
private Properties table;
private JTextArea displayArea;
private JTextField valueField, nameField;
// 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

Outline

northSubPanel.add( new JLabel( "Property name (key)" ) );


nameField = new JTextField( 10 );
northSubPanel.add( nameField );

PropertiesTest.
java

JPanel northPanel = new JPanel();


northPanel.setLayout( new BorderLayout() );
northPanel.add( northSubPanel, BorderLayout.NORTH );
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

Outline

new ActionListener() { // anonymous inner class

// put name-value pair in Properties table


Properties method
public void actionPerformed( ActionEvent event )
PropertiesTest.
setProperty stores
{
value for the specifiedjava
key
Object value = table.setProperty(
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" );

Outline

listProperties();

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

Outline

table.store( output, "Sample Properties" );


output.close();
listProperties();
}

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

Outline

// load contents of table


try {
FileInputStream input =
new FileInputStream( "props.dat" );
table.load( input );
input.close();
listProperties();
}
// process problems with file input
catch( IOException ioException ) {
ioException.printStackTrace();
}

PropertiesTest.
java
Properties method
load
Line 179
restores Properties contents
from FileInputStream

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

PropertiesTest.
java
Line 207

while ( enumeration.hasMoreElements() ) {
name = enumeration.nextElement().toString();
value = table.getProperty( name );
buffer.append( name ).append( '\t' );
buffer.append( value ).append( '\n' );
}

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.

21.6 Bit Manipulation and the Bitwise


Operators
Bitwise operators

Used for bit manipulation


Used for getting down to bit-and-bytes level

2003 Prentice Hall, Inc. All rights reserved.

21.6 Bit Manipulation and the Bitwise


Operators (cont.)
Description
The bits in the result are set to 1 if the corresponding bits
in the two operands are both 1.
bitwise inclusive OR The bits in the result are set to 1 if at least one of the cor|
responding bits in the two operands is 1.
bitwise exclusive
The bits in the result are set to 1 if exactly one of the
^
OR
corresponding bits in the two operands is 1.
left shift
Shifts the bits of the first operand left by the number of
<<
bits specified by the second operand; fill from the right
with 0.
signed right shift
Shifts the bits of the first operand right by the number of
>>
bits specified by the second operand. If the first operand
is negative, 1s are filled in from the left; otherwise, 0s
are filled in from the left.
unsigned right shift Shifts the bits of the first operand right by the number of
>>>
bits specified by the second operand; 0s are filled in
from the left.
bitwise complement All 0 bits are set to 1, and all 1 bits are set to 0.
~
Fig. 21.5 Bitwise operators.

Operator
&

Name
bitwise AND

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

Outline

// Fig. 21.6: PrintBits.java


// Printing an unsigned integer in bits.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

PrintBits.java

public class PrintBits extends JFrame {


private JTextField outputField;
// set up GUI
public PrintBits()
{
super( "Printing bit representations for numbers" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( new JLabel( "Enter an integer " ) );
// textfield to read value from user
JTextField inputField = new JTextField( 10 );
container.add( inputField );
inputField.addActionListener(
new ActionListener() { // anonymous inner class

2003 Prentice Hall, Inc.


All rights reserved.

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

// read integer and get bitwise representation


public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( event.getActionCommand() );
outputField.setText( getBits( value ) );
}
} // end anonymous inner class
); // end call to addActionListener

PrintBits.java

Lines 31-32
Convert String to int, then pass
Line
55 getBits
int to private
method
to get the ints bit representation

container.add( new JLabel( "The integer in bits is" ) );


// textfield to display integer in bitwise form
outputField = new JTextField( 33 );
outputField.setEditable( false );
container.add( outputField );
setSize( 720, 70 );
setVisible( true );

1 << 31 equals 10000000 00000000 00000000 00000000

} // end constructor
// display bit representation of specified int value
private String getBits( int value )
{
// create int value with 1 in leftmost bit and 0s elsewhere
int displayMask = 1 << 31;

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
79
80
81

StringBuffer buffer = new StringBuffer( 35 ); // buffer for output

Outline

// for each bit append 0 or 1 to buffer


for ( int bit = 1; bit <= 32; bit++ ) {

PrintBits.java
Line 63

// use displayMask to isolate bit


buffer.append( ( value & displayMask ) == 0 ? '0' : '1' );

Line 65

value <<= 1; // shift value one position to left


if ( bit % 8 == 0 )
buffer.append( ' ' ); Use
// append
bitwisespace
ANDto(&)buffer
to combine
every 8 bits
}

each bit in value and 1 << 31


Shift value one position to left

return buffer.toString();
} // end method getBits
public static void main( String args[] )
{
PrintBits application = new PrintBits();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class PrintBits

2003 Prentice Hall, Inc.


All rights reserved.

Outline
PrintBits.java

Program Output

2003 Prentice Hall, Inc.


All rights reserved.

21.6 Bit manipulation and the Bitwise


Operators (cont.)

Bit 1
0
1
0
1
Fig. 21.7

Bit 1 & Bit 2


Bit 2
0
0
0
0
1
0
1
1
Bitwise AND operator (&) combining two bits.

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

Outline

// Fig. 21.8: MiscBitOps.java


// Using the bitwise operators.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

MiscBitOps.java

public class MiscBitOps extends JFrame {


private JTextField input1Field, input2Field,
bits1Field, bits2Field, bits3Field, resultField;
private int value1, value2;
// set up GUI
public MiscBitOps()
{
super( "Bitwise operators" );
JPanel inputPanel = new JPanel();
inputPanel.setLayout( new GridLayout( 4, 2 ) );
inputPanel.add( new JLabel( "Enter 2 ints" ) );
inputPanel.add( new JLabel( "" ) );
inputPanel.add( new JLabel( "Value 1" ) );
input1Field = new JTextField( 8 );
inputPanel.add( input1Field );
inputPanel.add( new JLabel( "Value 2" ) );
input2Field = new JTextField( 8 );
inputPanel.add( input2Field );

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
59
60
61

inputPanel.add( new JLabel( "Result" ) );


resultField = new JTextField( 8 );
resultField.setEditable( false );
inputPanel.add( resultField );

Outline
MiscBitOps.java

JPanel bitsPanel = new JPanel();


bitsPanel.setLayout( new GridLayout( 4, 1 ) );
bitsPanel.add( new JLabel( "Bit representations" ) );
bits1Field = new JTextField( 33 );
bits1Field.setEditable( false );
bitsPanel.add( bits1Field );
bits2Field = new JTextField( 33 );
bits2Field.setEditable( false );
bitsPanel.add( bits2Field );
bits3Field = new JTextField( 33 );
bits3Field.setEditable( false );
bitsPanel.add( bits3Field );
JPanel buttonPanel = new JPanel();
// button to perform bitwise AND
JButton andButton = new JButton( "AND" );
buttonPanel.add( andButton );
andButton.addActionListener(
new ActionListener() { // anonymous inner class

2003 Prentice Hall, Inc.


All rights reserved.

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
88
89
90
91
92
93

// perform bitwise AND and display results


public void actionPerformed( ActionEvent event )
Use bitwise AND (&) to combine
{
value1 and value2
setFields();
resultField.setText( Integer.toString( value1 & value2 ) );
MiscBitOps.java
bits3Field.setText( getBits( value1 & value2 ) );
}

Outline

} // end anonymous inner class

Lines 66 and 67

); // end call to addActionListener

Lines 86 and 87

// button to perform bitwise inclusive OR


JButton inclusiveOrButton = new JButton( "Inclusive OR" );
buttonPanel.add( inclusiveOrButton );
inclusiveOrButton.addActionListener(
new ActionListener() { // anonymous inner class
// perform bitwise inclusive OR and display results Use bitwise inclusive OR (|) to
public void actionPerformed( ActionEvent event )
combine value1 and value2
{
setFields();
resultField.setText( Integer.toString( value1 | value2 ) );
bits3Field.setText( getBits( value1 | value2 ) );
}
} // end anonymous inner class
); // end call to addActionListener

2003 Prentice Hall, Inc.


All rights reserved.

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
119
120
121
122
123
124

// button to perform bitwise exclusive OR


JButton exclusiveOrButton = new JButton( "Exclusive OR" );
buttonPanel.add( exclusiveOrButton );

Outline
MiscBitOps.java

exclusiveOrButton.addActionListener(
new ActionListener() { // anonymous inner class

Lines 106
107
OR and
(^) to
// perform bitwise exclusive OR and display results Use bitwise exclusive
public void actionPerformed( ActionEvent event )
combine value1 and value2
{
setFields();
resultField.setText( Integer.toString( value1 ^ value2 ) );
bits3Field.setText( getBits( value1 ^ value2 ) );
}
} // end anonymous inner class
); // end call to addActionListener
// button to perform bitwise complement
JButton complementButton = new JButton( "Complement" );
buttonPanel.add( complementButton );
complementButton.addActionListener(
new ActionListener() { // anonymous inner class
// perform bitwise complement and display results
public void actionPerformed( ActionEvent event )
{

2003 Prentice Hall, Inc.


All rights reserved.

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

input2Field.setText( "" );
bits2Field.setText( "" );

Outline

int value = Integer.parseInt( input1Field.getText() );


resultField.setText( Integer.toString( ~value ) );
bits1Field.setText( getBits( value ) );
bits3Field.setText( getBits( ~value ) );

MiscBitOps.java
Lines 130 and 132

}
} // end anonymous inner class

Use bitwise complement (~) on value

); // end call to addActionListener


Container container = getContentPane();
container.add( inputPanel, BorderLayout.WEST );
container.add( bitsPanel, BorderLayout.EAST );
container.add( buttonPanel, BorderLayout.SOUTH );
setSize( 600, 150 );
setVisible( true );
} // end constructor
// display numbers and their bit form
private void setFields()
{
value1 = Integer.parseInt( input1Field.getText() );
value2 = Integer.parseInt( input2Field.getText() );
bits1Field.setText( getBits( value1 ) );
bits2Field.setText( getBits( value2 ) );
}

2003 Prentice Hall, Inc.


All rights reserved.

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189

Outline

// display bit representation of specified int value


private String getBits( int value )
{
// create int value with 1 in leftmost bit and 0s elsewhere
int displayMask = 1 << 31;

MiscBitOps.java

StringBuffer buffer = new StringBuffer( 35 ); // buffer for output


// for each bit append 0 or 1 to buffer
for ( int bit = 1; bit <= 32; bit++ ) {
// use displayMask to isolate bit
buffer.append( ( value & displayMask ) == 0 ? '0' : '1' );
value <<= 1; // shift value one position to left
if ( bit % 8 == 0 )
buffer.append( ' ' ); // append space to buffer every 8 bits
}
return buffer.toString();
} // end method getBits
public static void main( String args[] )
{
MiscBitOps application = new MiscBitOps();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MiscBitOps

2003 Prentice Hall, Inc.


All rights reserved.

Outline
MiscBitOps.java

Program Output

2003 Prentice Hall, Inc.


All rights reserved.

21.6 Bit Manipulation and the Bitwise


Operators (cont.)

Bit 1
0
1
0
1
Fig. 21.9

Bit 1 | Bit 2
Bit 2
0
0
0
1
1
1
1
1
Bitwise inclusive OR operator (|) combining two bits.

2003 Prentice Hall, Inc. All rights reserved.

21.6 Bit Manipulation and the Bitwise


Operators (cont.)

Bit 1 ^ Bit 2
Bit 1
Bit 2
0
0
0
1
0
1
0
1
1
1
1
0
Fig. 21.10 Bitwise exclusive OR operator (^) combining two bits.

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

Outline

// Fig. 21.11: BitShift.java


// Using the bitwise shift operators.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

BitShift.java

public class BitShift extends JFrame {


private JTextField bitsField, valueField;
// set up GUI
public BitShift()
{
super( "Shifting bits" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( new JLabel( "Integer to shift " ) );
// textfield for user to input integer
valueField = new JTextField( 12 );
container.add( valueField );
valueField.addActionListener(
new ActionListener() { // anonymous inner class
// read value and display its bitwise representation
public void actionPerformed( ActionEvent event )
{

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
59
60

Outline

int value = Integer.parseInt( valueField.getText() );


bitsField.setText( getBits( value ) );
}

BitShift.java

} // end anonymous inner class

Line 56

); // end call to addActionListener


// textfield to display bitwise representation of an integer
bitsField = new JTextField( 33 );
bitsField.setEditable( false );
container.add( bitsField );
// button to shift bits left by one position
JButton leftButton = new JButton( "<<" );
container.add( leftButton );
leftButton.addActionListener(
new ActionListener() { // anonymous inner class

Use bitwise left-shift operator


(<<) to shift values bits to
the left by one position

// left shift one position and display new value


public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( valueField.getText() );
value <<= 1;
valueField.setText( Integer.toString( value ) );
bitsField.setText( getBits( value ) );
}

2003 Prentice Hall, Inc.


All rights reserved.

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
88
89
90
91
92

} // end anonymous inner class

Outline

); // end call to addActionListener


// button to signed right shift value one position
JButton rightSignButton = new JButton( ">>" );
container.add( rightSignButton );
rightSignButton.addActionListener(
new ActionListener() { // anonymous inner class

BitShift.java
Line 77
Use bitwise signed right-shift
(>>) to shift values bits to
the right by one position

// right shift one position and display new value


public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( valueField.getText() );
value >>= 1;
valueField.setText( Integer.toString( value ) );
bitsField.setText( getBits( value ) );
}
} // end anonymous inner class
); // end call to addActionListener
// button to unsigned right shift value one position
JButton rightZeroButton = new JButton( ">>>" );
container.add( rightZeroButton );
rightZeroButton.addActionListener(
new ActionListener() { // anonymous inner class

2003 Prentice Hall, Inc.


All rights reserved.

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
119
120

// right shift one position and display new value


public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( valueField.getText() );
value >>>= 1;
valueField.setText( Integer.toString( value ) );

Outline

bitsField.setText( getBits( value ) );


}
} // end anonymous inner class

BitShift.java
Line 98

Use bitwise unsigned rightshift (>>>) to shift values


bits to the right by one position

); // end call to addActionListener


setSize( 400, 120 );
setVisible( true );
} // end constructor
// display bit representation of specified int value
private String getBits( int value )
{
// create int value with 1 in leftmost bit and 0s elsewhere
int displayMask = 1 << 31;
StringBuffer buffer = new StringBuffer( 35 ); // buffer for output

2003 Prentice Hall, Inc.


All rights reserved.

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143

Outline

// for each bit append 0 or 1 to buffer


for ( int bit = 1; bit <= 32; bit++ ) {
// use displayMask to isolate bit
buffer.append( ( value & displayMask ) == 0 ? '0' : '1' );

BitShift.java
Program Output

value <<= 1; // shift value one position to left


if ( bit % 8 == 0 )
buffer.append( ' ' ); // append space to buffer every 8 bits
}
return buffer.toString();
} // end method getBits
public static void main( String args[] )
{
BitShift application = new BitShift();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class BitShift

2003 Prentice Hall, Inc.


All rights reserved.

Outline
BitShift.java

Program Output

2003 Prentice Hall, Inc.


All rights reserved.

21.6 Bit Manipulation and the Bitwise


Operator (cont.)

Bitwise
assignment
operators
Bitwise AND assignment operator.
&=
Bitwise inclusive OR assignment operator.
|=
Bitwise exclusive OR assignment operator.
^=
Left-shift assignment operator.
<<=
Signed right-shift assignment operator.
>>=
Unsigned right-shift assignment operator.
>>>=
Fig. 21.12 Bitwise assignment operators.

2003 Prentice Hall, Inc. All rights reserved.

21.7 BitSet class


BitSet

Facilitates the creation and manipulation of bit sets


Represent set of boolean flags
Dynamically resizable

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

Outline

// Fig. 21.13: BitSetTest.java


// Using a BitSet to demonstrate the Sieve of Eratosthenes.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

BitSetTest.java
Line 18

public class BitSetTest extends JFrame {


private BitSet sieve;
private JLabel statusLabel;
private JTextField inputField;
// set up GUI
public BitSetTest()
{
super( "BitSets" );
sieve = new BitSet( 1024 );

Create bitset of 1024 bits

Container container = getContentPane();


statusLabel = new JLabel( "" );
container.add( statusLabel, BorderLayout.SOUTH );
JPanel inputPanel = new JPanel();
inputPanel.add( new JLabel( "Enter a value from 2 to 1023" ) );

2003 Prentice Hall, Inc.


All rights reserved.

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
56

Outline

// textfield for user to input a value from 2 to 1023


inputField = new JTextField( 10 );
inputPanel.add( inputField );
container.add( inputPanel, BorderLayout.NORTH );

BitSetTest.java

inputField.addActionListener(
new ActionListener() { // inner class
// determine whether value is prime number
public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( inputField.getText() );
if ( sieve.get( value ) )
statusLabel.setText( value + " is a prime number" );
else
statusLabel.setText( value + " is not a prime number" );
}
} // end inner class
); // end call to addActionListener
JTextArea primesArea = new JTextArea();
container.add( new JScrollPane( primesArea ), BorderLayout.CENTER );

2003 Prentice Hall, Inc.


All rights reserved.

57
58
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

Outline

int size = sieve.size(); // set all bits from 2 to 1023


for ( int i = 2; i < size; i++ )
sieve.set( i );

Use method set to turn


on all bits in BitSet

// perform Sieve of Eratosthenes


int finalBit = ( int ) Math.sqrt( size );

BitSetTest.java
Lines 59-60

for ( int i = 2; i < finalBit; i++ )


if ( sieve.get( i ) )

Lines 63-70
Determine prime numbers

for ( int j = 2 * i; j < size; j += i )


sieve.clear( j );
int counter = 0; // display prime numbers from 2 to 1023
for ( int i = 2; i < size; i++ )
if ( sieve.get( i ) ) {
primesArea.append( String.valueOf( i ) );
primesArea.append( ++counter % 7 == 0 ? "\n" : "\t" );
}
setSize( 600, 450 );
setVisible( true );
} // end constructor

2003 Prentice Hall, Inc.


All rights reserved.

86
87
88
89
90
91
92

Outline

public static void main( String args[] )


{
BitSetTest application = new BitSetTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

BitSetTest.java

} // end class BitSetTest

2003 Prentice Hall, Inc.


All rights reserved.

Вам также может понравиться