You are on page 1of 67

Chapter 20 Java Utilities Package and Bit Manipulation

Outline 20.1 20.2 20.3 20.4 20.5 20.6 20.7 20.8 20.9 Introduction Vector Class and Enumeration Interface Stack Class Dictionary Class Hashtable Class Properties Class Random Class Bit Manipulation and the Bitwise Operators BitSet Class

2002 Prentice Hall, Inc. All rights reserved.

20.1 Introduction Utility classes and interfaces


Contained in package java.util
Class Vector Interface Enumeration Class Stack Class Dictionary Class Hashtable Class Properties Class Random Class BitSet

2002 Prentice Hall, Inc. All rights reserved.

20.2 Vector Class and Enumeration Interface Class java.util.Vector


Array-like data structure that can resize itself dynamically Contains a capacity Grows by capacity increment if it requires additional space

2002 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 31 32 33 34 35

// Fig. 20.1: VectorTest.java // Testing the Vector class of the java.util package // Java core packages import java.util.*; import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*; public class VectorTest extends JFrame { private JLabel statusLabel; private Vector vector; private JTextField inputField; // set up GUI to test Vector methods public VectorTest() { super( "Vector Example" ); Container container = getContentPane(); container.setLayout( new FlowLayout() ); statusLabel = new JLabel(); vector = new Vector( 1 ); container.add( new JLabel( "Enter a string" ) ); inputField = new JTextField( 10 ); container.add( inputField ); // button to add element to vector JButton addButton = new JButton( "Add" );

Outline
Fig. 20.1 Demonstrating class Vector of package java.util. Line 26

Create Vector with initial capacity of one element

2002 Prentice Hall, Inc.


All rights reserved.

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 62 63 64 65 66 67 68 69 70

addButton.addActionListener(

Outline
Fig. 20.1 Demonstrating Vector method class Vector of addElement appends package Object to Vector java.util (Part 2). Line 43 Lines 63-65

new ActionListener() {
public void actionPerformed( ActionEvent event ) { // add an element to vector vector.addElement( inputField.getText() ); statusLabel.setText( "Added to end: " + inputField.getText() ); inputField.setText( "" ); } } ); // end call to addActionListener container.add( addButton ); // button to remove element from vector JButton removeButton = new JButton( "Remove" ); removeButton.addActionListener( new ActionListener() {

public void actionPerformed( ActionEvent event ) { // remove element from vector if ( vector.removeElement( inputField.getText() ) ) statusLabel.setText( "Removed: " + inputField.getText() ); else statusLabel.setText( inputField.getText() + " not in vector" ); }

Vector method removeElement removes Object from Vector

2002 Prentice Hall, Inc.


All rights reserved.

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

); // end call to addActionListener

Outline
Fig. 20.1 Demonstrating class Vector of package java.util (Part 3).

container.add( removeButton );
// button to get first element of vector JButton firstButton = new JButton( "First" ); firstButton.addActionListener( new ActionListener() {

public void actionPerformed( ActionEvent event ) Vector method Line 87 { firstElement obtains // return first element of vector first Object in Vector try { statusLabel.setText( "First element: " + vector.firstElement() ); } // catch exception if Vector empty catch ( NoSuchElementException exception ) { statusLabel.setText( exception.toString() ); } } } ); // end call to addActionListener container.add( firstButton ); // button to get last element of vector JButton lastButton = new JButton( "Last" ); lastButton.addActionListener(

2002 Prentice Hall, Inc.


All rights reserved.

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

new ActionListener() {

Outline
Vector method lastElement obtains Fig. 20.1 last Object in Vector Demonstrating
class Vector of package java.util (Part 4). Line 112 Line 135

public void actionPerformed( ActionEvent event ) { // return last element of vector try { statusLabel.setText( "Last element: " + vector.lastElement() ); } // catch exception if Vector empty catch ( NoSuchElementException exception ) { statusLabel.setText( exception.toString() ); }
} } ); // end call to addActionListener

container.add( lastButton );
// button to determine whether vector is empty JButton emptyButton = new JButton( "Is Empty?" ); emptyButton.addActionListener( new ActionListener() {

Vector method isEmpty returns boolean that indicates whether Vector contains any Objects

public void actionPerformed( ActionEvent event ) { // determine if Vector is empty statusLabel.setText( vector.isEmpty() ? "Vector is empty" : "Vector is not empty" ); } } ); // end call to addActionListener

2002 Prentice Hall, Inc.


All rights reserved.

140 141 142 143 144 145 146 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

container.add( emptyButton ); // button to determine whether vector contains search key JButton containsButton = new JButton( "Contains" );

Outline

Fig. 20.1 Demonstrating containsButton.addActionListener( class Vector of package Vector method contains returns new ActionListener() { java.util (Part boolean that indicates whether 5). public void actionPerformed( ActionEvent event ) Vector contains a specific Object { Line 155 String searchKey = inputField.getText();
// determine if Vector contains searchKey if ( vector.contains( searchKey ) ) statusLabel.setText( "Vector contains " + searchKey ); else statusLabel.setText( "Vector does not contain " + searchKey ); } } ); // end call to addActionListener container.add( containsButton ); // button to determine location of value in vector JButton locationButton = new JButton( "Location" ); locationButton.addActionListener( new ActionListener() {

2002 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 201 202 203 204 205 206 207

public void actionPerformed( ActionEvent event ) { // get location of an object in Vector statusLabel.setText( "Element is at location " + vector.indexOf( inputField.getText() ) ); } } ); // end call to addActionListener container.add( locationButton ); // button to trim vector size JButton trimButton = new JButton( "Trim" ); trimButton.addActionListener( new ActionListener() {

Outline

Fig. 20.1 Demonstrating class Vector of package Vector method indexOf java.util (Part 6). returns index of first location in Vector containing the argument Line 178 Line 195

public void actionPerformed( ActionEvent event ) { // remove unoccupied elements to save memory vector.trimToSize(); statusLabel.setText( "Vector trimmed to size" ); }
} ); container.add( trimButton );

Vector method trimToSize reduces the Vector capacity to the current number of elements in Vector

// button to display vector size and capacity JButton statsButton = new JButton( "Statistics" ); statsButton.addActionListener(

2002 Prentice Hall, Inc.


All rights reserved.

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 233 234 235 236 237 238 239 240 241 242

new ActionListener() {

Outline
Fig. 20.1 Demonstrating class Vector of package Vector methods size and java.util (Part 7). capacity return number of Objects in Vector and VectorLines 213-214 capacity, respectively Line 231

public void actionPerformed( ActionEvent event ) { // get size and capacity of Vector statusLabel.setText( "Size = " + vector.size() + "; capacity = " + vector.capacity() ); }
} ); // end call to addActionListener container.add( statsButton ); // button to display vector contents JButton displayButton = new JButton( "Display" ); displayButton.addActionListener(

new ActionListener() {
public void actionPerformed( ActionEvent event ) { // use Enumeration to output Vector contents Enumeration enum = vector.elements(); StringBuffer buf = new StringBuffer();

Vector method elements returns Enumeration for iterating Vector elements


" );

while ( enum.hasMoreElements() ) buf.append( enum.nextElement() ).append( "


JOptionPane.showMessageDialog( null, buf.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); // end call to addActionListener

2002 Prentice Hall, Inc.


All rights reserved.

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

container.add( displayButton ); container.add( statusLabel ); setSize( 300, 200 ); setVisible( true ); } // end VectorTest constructor

Outline
Fig. 20.1 Demonstrating class Vector of package java.util (Part 8).

// execute application public static void main( String args[] ) { VectorTest application = new VectorTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }

// end class VectorTest

Program Output

2002 Prentice Hall, Inc.


All rights reserved.

20.3 Stack Class Stack


Implements stack data structure Extends class Vector Stores references to Objects (as does Vector)

2002 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 31 32 33 34

// Fig. 20.2: StackTest.java // Testing the Stack class of the java.util package // Java core packages import java.awt.*; import java.awt.event.*; import java.util.*; // Java extension packages import javax.swing.*; public class StackTest extends JFrame { private JLabel statusLabel; private JTextField inputField; private Stack stack; // create GUI to manipulate a Stack public StackTest() { super( "Stacks" ); Container container = getContentPane(); statusLabel = new JLabel(); stack = new Stack();

Outline
Fig. 20.2 Demonstrating class Stack of package java.util. Line 25

Create empty Stack

container.setLayout( new FlowLayout() ); container.add( new JLabel( "Enter a string" ) ); inputField = new JTextField( 10 ); container.add( inputField );
// button to place object on stack JButton pushButton = new JButton( "Push" );

2002 Prentice Hall, Inc.


All rights reserved.

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 62 63 64 65 66 67 68 69

pushButton.addActionListener(

Outline
Fig. 20.2 Demonstrating class Stack of Stack method push package adds Object argument java.util to top of Stack (Part 2). Line 43 Line 61

new ActionListener() {
public void actionPerformed( ActionEvent event ) { // put object on Stack statusLabel.setText( "Pushed: " + stack.push( inputField.getText() ) ); }

}
); container.add( pushButton ); // button to remove top object on stack JButton popButton = new JButton( "Pop" );

popButton.addActionListener(
new ActionListener() {

Stack method pop removes public void actionPerformed( ActionEvent event ) { Object from top of Stack // remove element from Stack try { statusLabel.setText( "Popped: " + stack.pop() ); }
// process exception if Stack empty catch ( EmptyStackException exception ) { statusLabel.setText( exception.toString() ); } }

2002 Prentice Hall, Inc.


All rights reserved.

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

);

Outline
Fig. 20.2 Demonstrating Stack method peek returns class Stack of Object from top of Stack, package without removing that Object java.util (Part 3). Line 85

container.add( popButton );
// button to look at top element of stack JButton peekButton = new JButton( "Peek" ); peekButton.addActionListener( new ActionListener() {

public void actionPerformed( ActionEvent event ) { // look at top object on Stack try { statusLabel.setText( "Top: " + stack.peek() ); }

// process exception if Stack empty catch ( EmptyStackException exception ) { statusLabel.setText( exception.toString() ); }


} } );

container.add( peekButton );
// button to determine whether stack is empty JButton emptyButton = new JButton( "Is Empty?" ); emptyButton.addActionListener( new ActionListener() {

2002 Prentice Hall, Inc.


All rights reserved.

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

public void actionPerformed( ActionEvent event ) { // determine if Stack is empty statusLabel.setText( stack.empty() ? "Stack is empty" : "Stack is not empty" ); } } ); container.add( emptyButton ); // button to determine whether search key is in stack JButton searchButton = new JButton( "Search" ); searchButton.addActionListener( new ActionListener() {

Outline
Fig. 20.2 Demonstrating class Stack of Stack method empty returns package boolean that indicates whether java.util (Part Stack contains any Objects4). Line 108 Line 127

public void actionPerformed( ActionEvent event ) { // search Stack for specified object String searchKey = inputField.getText(); int result = stack.search( searchKey );

if ( result == -1 ) statusLabel.setText( searchKey + " not found" ); else statusLabel.setText( searchKey + " found at element " + result ); } } ); container.add( searchButton );

Stack method search returns boolean that indicates whether Stack contains specific Object argument

2002 Prentice Hall, Inc.


All rights reserved.

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

// button to display stack contents JButton displayButton = new JButton( "Display" ); displayButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { // output Stack contents Enumeration enumeration = stack.elements(); StringBuffer buffer = new StringBuffer(); while ( enumeration.hasMoreElements() ) buffer.append( enumeration.nextElement() ).append( " " ); JOptionPane.showMessageDialog( null, buffer.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); container.add( displayButton ); container.add( statusLabel ); setSize( 675, 100 ); setVisible( true ); }

Outline
Fig. 20.2 Demonstrating class Stack of package java.util (Part 5). Line 150

Stack extends Vector, so class Stack may use method elements to obtain Enumeration for Stack

2002 Prentice Hall, Inc.


All rights reserved.

171 172 173 174 175 176 177 178 179 180

// execute application public static void main( String args[] ) { StackTest application = new StackTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class StackTest

Outline
Fig. 20.2 Demonstrating class Stack of package java.util (Part 6).

Program Output

2002 Prentice Hall, Inc.


All rights reserved.

20.4 Dictionary Class Dictionary


Maps keys to values Provides public interface
Methods required to maintain table of key-value pairs

abstract class Superclass of class Hashtable

2002 Prentice Hall, Inc. All rights reserved.

20.5 Hashtable Class Hashtable


Data structure that use 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

2002 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 31 32 33 34

// Fig. 20.3: HashtableTest.java // Demonstrates class Hashtable of the java.util package. // Java core packages import java.awt.*; import java.awt.event.*; import java.util.*; // Java extensions packages import javax.swing.*; public class HashtableTest extends JFrame { private JLabel statusLabel; private Hashtable table; private JTextArea displayArea; private JTextField lastNameField; private JTextField firstNameField;

Outline
Fig. 20.3 Demonstrating class Hashtable. Line 25

// set up GUI to demonstrate Hashtable features public HashtableTest() { super( "Hashtable Example" );
statusLabel = new JLabel(); table = new Hashtable(); displayArea = new JTextArea( 4, 20 ); displayArea.setEditable( false ); JPanel northSubPanel = new JPanel(); northSubPanel.add( new JLabel( "First name" ) ); firstNameField = new JTextField( 8 ); northSubPanel.add( firstNameField );

Create empty Hashtable

2002 Prentice Hall, Inc.


All rights reserved.

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 62 63 64 65 66

northSubPanel.add( new JLabel( "Last name (key)" ) ); lastNameField = new JTextField( 8 ); northSubPanel.add( lastNameField ); JPanel northPanel = new JPanel(); northPanel.setLayout( new BorderLayout() ); northPanel.add( northSubPanel, BorderLayout.NORTH ); northPanel.add( statusLabel, BorderLayout.SOUTH ); JPanel southPanel = new JPanel(); southPanel.setLayout( new GridLayout( 2, 5 ) ); JButton putButton = new JButton( "Put" ); putButton.addActionListener( new ActionListener() {

Outline
Fig. 20.3 Demonstrating class Hashtable (Part 2).

Lines 59-60 Hashtable method put adds key and value to Hashtable (returns null if key has been inserted previously)

// add new key/value pair to hash table public void actionPerformed( ActionEvent event ) { Employee employee = new Employee( firstNameField.getText(), lastNameField.getText() ); Object value = table.put( lastNameField.getText(), employee ); // first time this key was added if ( value == null ) statusLabel.setText( "Put: " + employee.toString() );

2002 Prentice Hall, Inc.


All rights reserved.

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 94 95 96 97 98 99 100 101

// replaced previous value for this key else statusLabel.setText( "Put: " + employee.toString() + "; Replaced: " + value.toString() ); } } ); southPanel.add( putButton ); // button to get value for specific key JButton getButton = new JButton( "Get" ); getButton.addActionListener( new ActionListener() {

Outline
Fig. 20.3 Demonstrating class Hashtable (Part 3).

Line 88 Hashtable method get obtains Object associated with key from Hashtable (returns null if neither key nor Object exist)

// get value for specific key public void actionPerformed( ActionEvent event ) { Object value = table.get( lastNameField.getText() );
// value found for key if ( value != null ) statusLabel.setText( "Get: " + value.toString() ); // value not found for key else statusLabel.setText( "Get: " + lastNameField.getText() + " not in table" ); }

2002 Prentice Hall, Inc.


All rights reserved.

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

);

Outline
Fig. 20.3 Demonstrating class Hashtable Hashtable (Part 4). method remove removes Object associated with key argument from Hashtable Lines 116-117

southPanel.add( getButton );
// button to remove key/value pair from table JButton removeButton = new JButton( "Remove" ); removeButton.addActionListener( new ActionListener() {

// remove key/value pair public void actionPerformed( ActionEvent event ) { Object value = table.remove( lastNameField.getText() ); // key found if ( value != null ) statusLabel.setText( "Remove: " + value.toString() );

// key not found else statusLabel.setText( "Remove: " + lastNameField.getText() + " not in table" );

}
} ); southPanel.add( removeButton ); // button to detetmine whether hash table is empty JButton emptyButton = new JButton( "Empty" );

2002 Prentice Hall, Inc.


All rights reserved.

137 138 139 140 141 142 143 144 145 146 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

emptyButton.addActionListener(

Hashtable method isEmpty returns Outline boolean that indicates whether new ActionListener() { Hashtable contains any Objects Fig. 20.3 // determine whether hash table is empty public void actionPerformed( ActionEvent event ) Demonstrating { class Hashtable statusLabel.setText( "Empty: " + table.isEmpty() ); (Part 5). }
}

);
southPanel.add( emptyButton );

Line 144
Lines 161-162

// button to determine whether hash table contains key JButton containsKeyButton = new JButton( "Contains key" ); containsKeyButton.addActionListener( new ActionListener() {

Hashtable method containsKey returns boolean that indicates whether Hashtable contains key argument

// determine whether hash table contains key public void actionPerformed( ActionEvent event ) { statusLabel.setText( "Contains key: " + table.containsKey( lastNameField.getText() ) ); } } ); southPanel.add( containsKeyButton ); // button to clear all hash table contents JButton clearButton = new JButton( "Clear table" );

2002 Prentice Hall, Inc.


All rights reserved.

172 173 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 201 202 203 204 205 206

clearButton.addActionListener(

Outline
Fig. 20.3 Demonstrating class Hashtable (Part 6).

new ActionListener() {
// clear hash table contents public void actionPerformed( ActionEvent event ) { table.clear(); statusLabel.setText( "Clear: Table is now empty" ); }

}
); southPanel.add( clearButton );

Hashtable methodLine 179removes clear all elements from Hashtable


Lines 199-200

// button to display hash table elements JButton listElementsButton = new JButton( "List objects" );

listElementsButton.addActionListener(
new ActionListener() {

Hashtable method elements obtains Enumeration of Hashtable values

// display hash table elements public void actionPerformed( ActionEvent event ) { StringBuffer buffer = new StringBuffer(); for ( Enumeration enumeration = table.elements(); enumeration.hasMoreElements(); ) buffer.append( enumeration.nextElement() ).append( '\n' ); displayArea.setText( buffer.toString() ); }

2002 Prentice Hall, Inc.


All rights reserved.

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 233 234 235 236 237 238 239 240 241

);

Outline
Fig. 20.3 Demonstrating class Hashtable Hashtable method keys obtains (Part 7). Enumeration of Hashtable keys

southPanel.add( listElementsButton );
// button to display hash table keys JButton listKeysButton = new JButton( "List keys" ); listKeysButton.addActionListener( new ActionListener() {

// display hash table KEYS public void actionPerformed( ActionEvent event ) { StringBuffer buffer = new StringBuffer(); for ( Enumeration enumeration = table.keys(); enumeration.hasMoreElements(); ) buffer.append( enumeration.nextElement() ).append( '\n' ); JOptionPane.showMessageDialog( null, buffer.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } }

Lines 223-224

);
southPanel.add( listKeysButton ); Container container = getContentPane(); container.add( northPanel, BorderLayout.NORTH ); container.add( new JScrollPane( displayArea ), BorderLayout.CENTER ); container.add( southPanel, BorderLayout.SOUTH );

2002 Prentice Hall, Inc.


All rights reserved.

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

setSize( 540, 300 ); setVisible( true ); } // execute application public static void main( String args[] ) { HashtableTest application = new HashtableTest();

Outline
Fig. 20.3 Demonstrating class Hashtable (Part 8).

application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} } // end class HashtableTest

// Employee class to represent first and last name class Employee { private String first, last; // initialize an Employee public Employee( String firstName, String lastName ) { first = firstName; last = lastName; } // convert Employee to String representation public String toString() { return first + " " + last; } } // end class Employee

2002 Prentice Hall, Inc.


All rights reserved.

Outline
Fig. 20.3 Demonstrating class Hashtable (Part 9).

Program Output

2002 Prentice Hall, Inc.


All rights reserved.

20.6 Properties Class Properties


Persistent Hashtable
Can be written to output stream and directed to file Can be read from file into input stream

Provides methods setProperty and getProperty


Store/obtain key-value pairs of Strings

2002 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 31 32 33 34 35

// Fig. 20.4: PropertiesTest.java // Demonstrates class Properties of the java.util package. // Java core packages import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; // Java extension packages import javax.swing.*; public class PropertiesTest extends JFrame { private JLabel statusLabel; private Properties table; private JTextArea displayArea; private JTextField valueField, nameField;

Outline
Fig. 20.4 Demonstrating class Properties. Line 25

// set up GUI to test Properties table public PropertiesTest() { super( "Properties Test" );
// create Properties table table = new Properties();

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

2002 Prentice Hall, Inc.


All rights reserved.

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 62 63 64 65 66 67 68 69 70

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

Outline
Fig. 20.4 Demonstrating class Properties (Part 2).

Lines 68-69

// 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" ); putButton.addActionListener( new ActionListener() { // put name/value pair in Properties table public void actionPerformed( ActionEvent event ) { Object value = table.setProperty( nameField.getText(), valueField.getText() );

Properties method setProperty stores value for the specified key

2002 Prentice Hall, Inc.


All rights reserved.

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

if ( value == null ) showstatus( "Put: " + nameField.getText() + " " + valueField.getText() ); else showstatus( "Put: " + nameField.getText() + " " + valueField.getText() + "; Replaced: " + value.toString() ); listProperties();

Outline
Fig. 20.4 Demonstrating class Properties (Part 3).

} } ); // end call to addActionListener


southPanel.add( putButton ); // button to empty contents of Properties table JButton clearButton = new JButton( "Clear" ); clearButton.addActionListener( new ActionListener() { // use method clear to empty table public void actionPerformed( ActionEvent event ) { table.clear(); showstatus( "Table in memory cleared" ); listProperties(); } } ); // end call to addActionListener southPanel.add( clearButton );

2002 Prentice Hall, Inc.


All rights reserved.

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

// button to get value of a property JButton getPropertyButton = new JButton( "Get property" ); getPropertyButton.addActionListener( new ActionListener() { // use method getProperty to obtain a property value public void actionPerformed( ActionEvent event ) { Object value = table.getProperty( nameField.getText() ); if ( value != null ) showstatus( "Get property: " + nameField.getText() + " " + value.toString() );

Outline
Fig. 20.4 Demonstrating class Properties (Part 4).

Lines 116-117 Properties method getProperty locates value associated with the specified key

else showstatus( "Get: " + nameField.getText() + " not in table" );


listProperties(); } } ); // end call to addActionListener southPanel.add( getPropertyButton ); // button to contents of Properties table to file JButton saveButton = new JButton( "Save" ); saveButton.addActionListener(

2002 Prentice Hall, Inc.


All rights reserved.

140 141 142 143 144 145 146 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

new ActionListener() {

Outline
Fig. 20.4 Demonstrating class Properties (Part 5).

// use method save to place contents in file public void actionPerformed( ActionEvent event ) { // save contents of table try { FileOutputStream output = new FileOutputStream( "props.dat" ); table.store( output, "Sample Properties" ); output.close();
listProperties(); } // process problems with file output catch( IOException ioException ) { ioException.printStackTrace(); } } } ); // end call to addActionListener southPanel.add( saveButton );

Line 150 Properties method store saves Properties contents to FileOutputStream

// button to load contents of Properties table from file JButton loadButton = new JButton( "Load" );
loadButton.addActionListener( new ActionListener() {

2002 Prentice Hall, Inc.


All rights reserved.

173 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 201 202 203 204 205 206 207

// use method load to read contents from file public void actionPerformed( ActionEvent event ) { // 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(); } } } ); // end call to addActionListener southPanel.add( loadButton ); container.add( southPanel, BorderLayout.SOUTH ); setSize( 550, 225 ); setVisible( true ); } // output property values public void listProperties() { StringBuffer buffer = new StringBuffer(); String name, value;

Outline
Fig. 20.4 Demonstrating class Properties (Part 6).

Properties method load Line 181 restores Properties contents from FileInputStream

2002 Prentice Hall, Inc.


All rights reserved.

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 233 234 235 236

Enumeration enumeration = table.propertyNames();

Outline

while ( enumeration.hasMoreElements() ) { name = enumeration.nextElement().toString(); value = table.getProperty( name );


buffer.append( name ).append( '\t' ); buffer.append( value ).append( '\n' ); }

displayArea.setText( buffer.toString() ); // end method ListProperties

Fig. 20.4 Demonstrating Properties method class Properties propertyNames obtains (Part 7). Enumeration of property names Line 208

// display String in statusLabel label public void showstatus( String s ) { statusLabel.setText( s ); } // execute application public static void main( String args[] ) { PropertiesTest application = new PropertiesTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

}
} // end class PropertiesTest

2002 Prentice Hall, Inc.


All rights reserved.

Outline
Fig. 20.4 Demonstrating class Properties (Part 8).

Program Output

2002 Prentice Hall, Inc.


All rights reserved.

20.7 Random Class Class Random


Provides (pseudo-) random-number generation
Random r = new Random();

Use seed to generate same random-number sequences


Random r = new Random( seedValue ); (useful when debugging)

Can generate distributed numbers uniformly


r.nextInt(); r.nextFloat();

Use % operator to scale generated number


e.g., rolling a six-sided die Math.abs( r.nextInt() ) % 6 + 1;

2002 Prentice Hall, Inc. All rights reserved.

20.8 Bit Manipulation and the Bitwise Operators Bitwise operators


Used for bit manipulation Used for getting down to bit-and-bytes level

2002 Prentice Hall, Inc. All rights reserved.

20.8 Bit Manipulation and the Bitwise Operators (cont.)


Op e ra to r Na m e De sc rip tio n

&

bitwise AND

The bits in the result are set to 1 if the corresponding bits in the two operands are both 1. The bits in the result are set to 1 if at least one of the corresponding bits in the two operands is 1. The bits in the result are set to 1 if exactly one of the corresponding bits in the two operands is 1. Shifts the bits of the first operand left by the number of bits specified by the second operand; fill from the right with 0 bits. 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 shifted in from the left; otherwise, 0s are shifted in from the left. Shifts the bits of the first operand right by the number of bits specified by the second operand; 0s are shifted in from the left. All 0 bits are set to 1 and all 1 bits are set to 0.

| ^ <<

bitwise inclusive OR bitwise exclusive OR left shift

>>

right shift with sign extension

>>>

right shift with zero extension ones complement The b itw ise op era tors.

~ Fig. 20.5

2002 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. 20.6: PrintBits.java // Printing an unsigned integer in bits // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*;

Outline
Fig. 20.6 Printing the bits in an integer.

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

inputField.addActionListener(
new ActionListener() {

2002 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 62 63 64 65

// read integer and get bitwise representation public void actionPerformed( ActionEvent event ) { int value = Integer.parseInt( event.getActionCommand() ); outputField.setText( getBits( value ) ); } } );

Outline

container.add( inputField );

Fig. 20.6 Printing the bits in an integer (Part 2). Convert String to int, then pass int to private method getBits Lines 34-35 to get the ints bit representation Line 58

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 ); } // 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; // buffer to build output StringBuffer buffer = new StringBuffer( 35 ); // for each bit append 0 or 1 to buffer for ( int bit = 1; bit <= 32; bit++ ) {

1 << 31 equals 10000000 00000000 00000000 00000000

2002 Prentice Hall, Inc.


All rights reserved.

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

// use displayMask to isolate bit and determine whether // bit has value of 0 or 1 buffer.append( ( value & displayMask ) == 0 ? '0' : '1' ); // shift value one position to left value <<= 1; // append space to buffer every 8 bits if ( bit % 8 == 0 ) buffer.append( ' ' ); } return buffer.toString(); } // execute application public static void main( String args[] ) { PrintBits application = new PrintBits(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class PrintBits

Outline
Fig. 20.6 Printing the bits in an integer (Part 3).

Use bitwise AND (&) to combine Line << each bit in value and 169 31

2002 Prentice Hall, Inc.


All rights reserved.

Outline
Fig. 20.6 Printing the bits in an integer (Part 4). Program Output

2002 Prentice Hall, Inc.


All rights reserved.

20.8 Bit manipulation and the Bitwise Operators (cont.)

Bit 1

Bit 2

Bit 1 & Bit 2

0 1 0 1 Fig. 20.7

0 0 1 1

0 0 0 1

Results of c om b ining two b its w ith the b itwise AND op e ra to r ( &).

2002 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 31 32 33 34 35

// Fig. 20.8: MiscBitOps.java // Using the bitwise AND, bitwise inclusive OR, bitwise // exclusive OR, and bitwise complement operators. // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*; 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 );

Outline
Fig. 20.8 Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators.

2002 Prentice Hall, Inc.


All rights reserved.

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 62 63 64 65

inputPanel.add( new JLabel( "Result" ) ); resultField = new JTextField( 8 ); resultField.setEditable( false ); inputPanel.add( resultField ); 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" );

Outline
Fig. 20.8 Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 2).

andButton.addActionListener(
new ActionListener() {

2002 Prentice Hall, Inc.


All rights reserved.

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 94 95 96 97 98

// perform bitwise AND and display results public void actionPerformed( ActionEvent eventUse bitwise AND (&) to combine ) { value1 and value2 setFields(); Fig. 20.8 resultField.setText( Integer.toString( value1 & value2 ) ); Demonstrating the bits3Field.setText( getBits( value1 & value2 ) ); bitwise AND, } } ); buttonPanel.add( andButton ); // button to perform bitwise inclusive OR JButton inclusiveOrButton = new JButton( "Inclusive OR" ); inclusiveOrButton.addActionListener(

Outline

bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 3). Line 71

new ActionListener() {

Line 91

// perform bitwise inclusive OR and display results public void actionPerformed( ActionEvent event Use bitwise inclusive OR (|) to ) { combine value1 and value2 setFields(); resultField.setText( Integer.toString( value1 | value2 ) ); bits3Field.setText( getBits( value1 | value2 ) ); } } ); buttonPanel.add( inclusiveOrButton );

2002 Prentice Hall, Inc.


All rights reserved.

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 125 126 127 128 129 130 131 132 133

// button to perform bitwise exclusive OR JButton exclusiveOrButton = new JButton( "Exclusive OR" ); exclusiveOrButton.addActionListener(

Outline

Fig. 20.8 new ActionListener() { Demonstrating the bitwise AND, // perform bitwise exclusive OR and display results bitwise inclusive public void actionPerformed( ActionEvent event Use bitwise exclusive OR (^) to ) { OR, and value2 combine value1 bitwise setFields(); exclusive OR and resultField.setText( bitwise complement Integer.toString( value1 ^ value2 ) ); bits3Field.setText( getBits( value1 ^ value2 ) ); operators (Part 4).
} }

);

Line 111

buttonPanel.add( exclusiveOrButton );
// button to perform bitwise complement JButton complementButton = new JButton( "Complement" ); complementButton.addActionListener( new ActionListener() { // perform bitwise complement and display results public void actionPerformed( ActionEvent event ) { input2Field.setText( "" ); bits2Field.setText( "" ); int value = Integer.parseInt( input1Field.getText() );

2002 Prentice Hall, Inc.


All rights reserved.

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

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

Outline

Fig. 20.8 ); Demonstrating Use bitwise complement (~) on value the bitwise AND, buttonPanel.add( complementButton ); bitwise inclusive Container container = getContentPane(); OR, bitwise container.add( inputPanel, BorderLayout.WEST ); exclusive OR and container.add( bitsPanel, BorderLayout.EAST ); bitwise complement container.add( buttonPanel, BorderLayout.SOUTH ); operators (Part 5).
setSize( 600, 150 ); setVisible( true ); }

Line 134

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

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

2002 Prentice Hall, Inc.


All rights reserved.

168 169 170 171 172 173 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

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

Outline
Fig. 20.8 Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 6).

2002 Prentice Hall, Inc.


All rights reserved.

Outline
Fig. 20.8 Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 7). Program Output

2002 Prentice Hall, Inc.


All rights reserved.

20.8 Bit Manipulation and the Bitwise Operators (cont.)


Bit 1 Bit 2 Bit 1 | Bit 2

0 1 0 1 Fig. 20.9

0 0 1 1

0 1 1 1

Results of c omb ining tw o b its w ith the b itw ise inc lusive OR op era tor ( |).

2002 Prentice Hall, Inc. All rights reserved.

20.8 Bit Manipulation and the Bitwise Operators (cont.)


Bit 1 Bit 2 Bit 1 ^ Bit 2

0 1 0 1

0 0 1 1

0 1 1 0

Fig. 20.10 Results of c omb ining tw o b its w ith the b itw ise exc lusive OR op era tor ( ^).

2002 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 31 32

// Fig. 20.11: BitShift.java // Using the bitwise shift operators. // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*;

Outline
Fig. 20.11 Demonstrating the bitwise shift operators.

public class BitShift extends JFrame { private JTextField bitsField; private JTextField 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() {

2002 Prentice Hall, Inc.


All rights reserved.

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 62 63 64 65 66

// read value and display its bitwise representation public void actionPerformed( ActionEvent event ) { int value = Integer.parseInt( valueField.getText() ); bitsField.setText( getBits( value ) ); } } ); // 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( "<<" ); leftButton.addActionListener( new ActionListener() { // 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 ) ); } } ); container.add( leftButton );

Outline
Fig. 20.11 Demonstrating the bitwise shift operators (Part 2).

Line 58

Use bitwise left-shift operator (<<) to shift values bits to the left by one position

2002 Prentice Hall, Inc.


All rights reserved.

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 94 95 96 97 98 99 100 101

// button to right shift value one position with sign extension JButton rightSignButton = new JButton( ">>" );

Outline

Use bitwise right-shift with signed extension operator (>>) rightSignButton.addActionListener( Fig. 20.11 to shift values bits to the new ActionListener() { Demonstrating the right by one position bitwise shift // right shift one position and display new value operators (Part 3). public void actionPerformed( ActionEvent event )
{

int value = Integer.parseInt( valueField.getText() ); value >>= 1; valueField.setText( Integer.toString( value ) ); bitsField.setText( getBits( value ) );
} } );

Line 78
Line 98

container.add( rightSignButton );
// button to right shift value one position with zero extension JButton rightZeroButton = new JButton( ">>>" ); rightZeroButton.addActionListener( new ActionListener() {

Use bitwise right-shift with unsigned extension operator (>>>) 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 ) );

2002 Prentice Hall, Inc.


All rights reserved.

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

} }

Outline
Fig. 20.11 Demonstrating the bitwise shift operators (Part 4).

);
container.add( rightZeroButton ); setSize( 400, 120 ); setVisible( true ); }

// 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;
// buffer to build output StringBuffer buffer = new StringBuffer( 35 ); // for each bit append 0 or 1 to buffer for ( int bit = 1; bit <= 32; bit++ ) { // use displayMask to isolate bit and determine whether // bit has value of 0 or 1 buffer.append( ( value & displayMask ) == 0 ? '0' : '1' ); // shift value one position to left value <<= 1; // append space to buffer every 8 bits if ( bit % 8 == 0 ) buffer.append( ' ' ); }

2002 Prentice Hall, Inc.


All rights reserved.

137 138 139 140 141 142 143 144 145 146 147 148 149

return buffer.toString(); } // execute application public static void main( String args[] ) { BitShift application = new BitShift(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

Outline
Fig. 20.11 Demonstrating the bitwise shift operators (Part 5).

}
} // end class BitShift

Program Output

2002 Prentice Hall, Inc.


All rights reserved.

Outline
Fig. 20.11 Demonstrating the bitwise shift operators (Part 6).

Program Output

2002 Prentice Hall, Inc.


All rights reserved.

20.8 Bit Manipulation and the Bitwise Operator (cont.)


Bitw ise a ssig nme nt o p e ra to rs

&= |= ^= <<= >>= >>>=

Bitwise AND assignment operator. Bitwise inclusive OR assignment operator. Bitwise exclusive OR assignment operator. Left shift assignment operator. Right shift with sign extension assignment operator. Right shift with zero extension assignment operator.

Fig. 20.12 The b itw ise a ssig nm ent op era tors.

2002 Prentice Hall, Inc. All rights reserved.

20.9 BitSet class BitSet


Facilitates the creation and manipulation of bit sets Represent set of boolean flags Dynamically resizable

2002 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 31 32 33 34 35

// Fig. 20.13: BitSetTest.java // Using a BitSet to demonstrate the Sieve of Eratosthenes. // Java core packages import java.awt.*; import java.awt.event.*; import java.util.*; // Java extension packages import javax.swing.*; 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 ); 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" ) ); // textfield for user to input a value from 2 to 1023 inputField = new JTextField( 10 );

Outline
Fig. 20.13 Demonstrating the Sieve of Eratosthenes using a BitSet. Line 22

Create bitset of 1024 bits

2002 Prentice Hall, Inc.


All rights reserved.

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 62 63 64 65 66 67 68 69 70

inputField.addActionListener( new ActionListener() { // determine whether value is prime number public void actionPerformed( ActionEvent event ) { int value = Integer.parseInt( inputField.getText() );

Outline
Fig. 20.13 Demonstrating the Sieve of Eratosthenes using a BitSet (Part 2). Lines 68-69

if ( sieve.get( value ) ) statusLabel.setText( value + " is a prime number" );


else statusLabel.setText( value + " is not a prime number" ); }

}
); inputPanel.add( inputField ); container.add( inputPanel, BorderLayout.NORTH ); JTextArea primesArea = new JTextArea();

container.add( new JScrollPane( primesArea ), BorderLayout.CENTER );


// set all bits from 1 to 1023 int size = sieve.size(); for ( int i = 2; i < size; i++ ) sieve.set( i );

Use method set to turn on all bits in BitSet 2002 Prentice Hall, Inc.
All rights reserved.

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

// perform Sieve of Eratosthenes int finalBit = ( int ) Math.sqrt( sieve.size() ); for ( int i = 2; i < finalBit; i++ ) if ( sieve.get( i ) ) for ( int j = 2 * i; j < size; j += i ) sieve.clear( j );

Outline
Fig. 20.13 Determine prime numbers Demonstrating the Sieve of Eratosthenes using a BitSet (Part 3). Lines 72-79

// display prime numbers from 1 to 1023 int counter = 0;


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 ); } // execute application public static void main( String args[] ) { BitSetTest application = new BitSetTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class BitSetTest

2002 Prentice Hall, Inc.


All rights reserved.

Outline
Fig. 20.13 Demonstrating the Sieve of Eratosthenes using a BitSet (Part 4). Program Output

2002 Prentice Hall, Inc.


All rights reserved.

You might also like