CS535 Object-Oriented Programming & Design
Fall Semester, 1996
Some Java Data Structures
[To Lecture Notes Index]
San Diego State University -- This page last updated Tuesday, 17 September, 1996
Contents of Some Java Data Structures
- References
- Classes by Type
- Classes by Package
- Containers
- Numeric Classes
- Vector
- Enumeration
- Vectors and Enumeration
- Stack
- Hashtable
- Some Useful Classes
- Random
- StringTokenizer
- BitSet
- Object
Core Java, Chapter 9
On-Line Java API documentation
Reading
Core Java, Chapter 9
GENERAL
Applet | DatagramSocket | ImageProducer | RandomAccessFile |
AppletContext | Date | IndexColorModel | Rectangle |
AppletStub | DebuggerCallback | InetAddress | Runnable |
AudioClip | Dialog | Insets | Runtime |
BitSet | Dictionary | Integer | RuntimeConstants |
Boolean | Dimension | Label | Scrollbar |
BorderLayout | DirectColorModel | LayoutManager | SecurityManager |
Button | Double | List | ServerSocket |
Canvas | Enumeration | LocalVariable | Socket |
CardLayout | Event | Long | SocketImpl |
Character | Field | Math | SocketImplFactory |
Checkbox | File | MediaTracker | Stack |
CheckboxGroup | FileDescriptor | MemoryImageSource | StackFrame |
CheckboxMenuItem | FileDialog | Menu | String |
Choice | FilenameFilter | MenuBar | StringBuffer |
Class | FilteredImageSource | MenuComponent | StringTokenizer |
ClassLoader | Float | MenuContainer | System |
Cloneable | FlowLayout | MenuItem | TextArea |
Color | Font | Number | TextComponent |
ColorModel | FontMetrics | Object | TextField |
Compiler | Frame | Observable | Thread |
Component | Graphics | Observer | ThreadDeath |
Constants | GridBagConstraints | Panel | ThreadGroup |
Container | GridBagLayout | PixelGrabber | Throwable |
ContentHandler | GridLayout | Point | Toolkit |
ContentHandlerFactory | Hashtable | Polygon | URL |
CropImageFilter | Image | Process | URLConnection |
DataInput | ImageConsumer | Properties | URLEncoder |
DataOutput | ImageFilter | RGBImageFilter | Vector |
DatagramPacket | ImageObserver | Random | Window |
STREAMS
BufferedInputStream | InputStream |
BufferedOutputStream | LineNumberInputStream |
ByteArrayInputStream | OutputStreamPipedInputStream |
ByteArrayOutputStream | PipedOutputStreamPrintStream |
DataInputStream | PushbackInputStream |
DataOutputStream | SequenceInputStreamStreamTokenizer |
FileInputStream | StringBufferInputStream |
FileOutputStream | URLStreamHandler |
FilterInputStream | URLStreamHandlerFactory |
FilterOutputStream | |
PEERS
ButtonPeer | FileDialogPeer | MenuPeer |
CanvasPeer | FramePeer | PanelPeer |
CheckboxMenuItemPeer | LabelPeer | ScrollbarPeer |
CheckboxPeer | ListPeer | TextAreaPeer |
ChoicePeer | MenuBarPeer | TextComponentPeer |
ComponentPeer | MenuComponentPeer | TextFieldPeer |
ContainerPeer | MenuItemPeer | WindowPeer |
DialogPeer | | |
REMOTES
RemoteArrayRemoteBoolean
RemoteByteRemoteChar
RemoteClassRemoteDebugger
RemoteDouble
RemoteFieldRemoteFloatRemoteInt
RemoteLongRemoteObject
RemoteShortRemoteStackFrame
RemoteStackVariableRemoteString
RemoteThreadRemoteThreadGroup
RemoteValue
class java.applet
Applet
AppletContext
AppletStub
AudioClip
class java.awt
AWTError | Event | Menu |
AWTException | FileDialog | MenuBar |
BorderLayout | FlowLayout | MenuComponent |
Button | Font | MenuItem |
Canvas | FontMetrics | Panel |
CardLayout | Frame | Point |
Checkbox | Graphics | Polygon |
CheckboxGroup | GridBagConstraints | Rectangle |
CheckboxMenuItem | GridBagLayout | Scrollbar |
Choice | GridLayout | TextArea |
Color | Image | TextComponent |
Component | Insets | TextField |
Container | Label | Toolkit |
Dialog | List | Window |
Dimension | MediaTracker | |
| | |
LayoutManager | MenuContainer |
class java.awt.image
ColorModel | IndexColorModel |
CropImageFilter | MemoryImageSource |
DirectColorModel | PixelGrabber |
FilteredImageSource | RGBImageFilter |
ImageFilter | ImageConsumer |
ImageObserver | ImageProducer |
class java.io
BufferedInputStream | FileNotFoundException | PipedInputStream |
BufferedOutputStream | FileOutputStream | PipedOutputStream |
ByteArrayInputStream | FilterInputStream | PrintStream |
ByteArrayOutputStream | FilterOutputStream | PushbackInputStream |
DataInputStream | InputStream | RandomAccessFile |
DataOutputStream | InterruptedIOException | SequenceInputStream |
EOFException | IOException | StreamTokenizer |
File | LineNumberInputStream | StringBufferInputStream |
FileDescriptor | OutputStream | UTFDataFormatException |
FileInputStream | | |
| | |
DataInput | DataOutput | FilenameFilter |
class java.lang
AbstractMethodError | IllegalMonitorStateException | OutOfMemoryError |
ArithmeticException | IllegalThreadStateException | Process |
ArrayIndexOutOfBoundsException | IncompatibleClassChangeError | RuntimeException |
ArrayStoreException | IndexOutOfBoundsException | SecurityException |
Boolean | InstantiationError | SecurityManager |
Character | InstantiationException | StackOverflowError |
Class | Integer | String |
ClassCastException | InternalError | StringBuffer |
ClassCircularityError | InterruptedException | StringIndexOutOfBoundsException |
ClassFormatError | LinkageError | System |
ClassLoader | Long | Thread |
ClassNotFoundException | Math | ThreadDeath |
CloneNotSupportedException | NegativeArraysizeException | ThreadGroup |
Compiler | NoClassDefFoundError | Throwable |
Double | NoSuchFieldError | UnknownError |
Error | NoSuchMethodError | UnsatisfiedLinkError |
Exception | NoSuchMethodException | VerifyError |
Float | NullPointerException | VirtualMachineError |
IllegalAccessError | Number | |
IllegalAccessException | NumberFormatException | |
IllegalArgumentException | Object | |
| | |
Cloneable | Runnable |
class java.net
ContentHandler | ServerSocket | UnknownServiceException |
DatagramPacket | Socket | URL |
DatagramSocket | SocketException | URLConnection |
InetAddress | SocketImpl | URLEncoder |
MalformedURLException | UnknownHostException | URLStreamHandler |
ProtocolException | | |
| | |
ContentHandlerFactory | SocketImplFactory | URLStreamHandlerFactory |
class java.util
BitSet | Hashtable | Random |
Date | NoSuchElementException | Stack |
Dictionary | Observable | StringTokenizer |
EmptyStackException | Properties | Vector |
| | |
Enumeration | Observer | |
class sun.tools.debug
Field | RemoteDouble | RemoteStackFrame |
LocalVariable | RemoteField | RemoteStackVariable |
RemoteArray | RemoteFloat | RemoteString |
RemoteBoolean | RemoteInt | RemoteThread |
RemoteByte | RemoteLong | RemoteThreadGroup |
RemoteChar | RemoteObject | RemoteValue |
RemoteClass | RemoteShort | StackFrame |
RemoteDebugger | | |
| | |
DebuggerCallback | Constants | RuntimeConstants |
The Container Problem
Containers, like linked list, are independent of the data type the contain.
How to build a container class that holds any type?
Pascal Like Solution
class IntLinkedListNode { //some code here }
class FloatLinkedListNode { //some code here }
etc.
C++/Ada Solution - Templates (Generic)
template <class DataType>
class LinkedListNode
{
DataType theData;
LinkedListNode* link;
// more code here
}
Java/Smalltalk Solution
Make class "Object" the ancestor of all classes
All classes are a subtype of Object
class LinkedListNode
{
Object theData;
LinkedListNode link;
}
class Student
{
String name;
}
class UseLinkedListNode
{
public static void main( String args[] )
{
LinkedListNode aNode = new LinkedListNode();
Student junior = new Student();
aNode.theData = junior;
Student senior = (Student) aNode.theData;
LinkedListNode aNumNode = new LinkedListNode();
aNumNode.theData = 5; //compile error, 5 not an object
aNode.link = aNumNode;
}
}
Java/Smalltalk Solution
Smalltalk solution: numbers are objects
Java solution
- int, float, long, etc. are not objects
-
- Classes Integer, Float, Double, Long are used to hold numbers
class UseLinkedListNode
{
public static void main( String args[] )
{
LinkedListNode aNumNode = new LinkedListNode();
aNumNode.theData = new Integer( 5 );
int result = ((Integer) aNumNode.theData).intValue();
}
}
Why Numeric Classes?
- "The numeric classes provide an object wrapper for numeric data values and
serves as a place for numeric-oriented operations. A wrapper is useful because
most of Java's utility classes require the use of objects. Since int, long,
float and double are not objects in Java, they need to be wrapped in a class
instance."
Numeric Classes Example
class NumericClassesExample
{
public static void main( String args[] )
{
Integer height = new Integer( 10 );
Integer width = new Integer( 25 );
Integer depth = 25; // Compile error
Integer area;
area = height * width; // Compile error
area = new Integer(height.intValue() * width.intValue() );
System.out.println( area );
String areaAsString = area.toString();
int areaAsInt = area.intValue();
long areaAsLong = area.longValue();
System.out.println( Integer.MAX_VALUE );
}
}
Some (not all) Numeric Operations
Class | Integer | Long |
| | |
Variables | MAX_VALUE | MAX_VALUE |
| MIN_VALUE | MIN_VALUE |
| | |
Constructors | Integer(int) | Long(long) |
| Integer(String) | Long(String) |
| | |
Methods | doubleValue() | doubleValue() |
| equals(Object) | equals(Object) |
| floatValue() | floatValue() |
| intValue() | intValue() |
| longValue() | longValue() |
| toString() | toString() |
| valueOf(String) | valueOf(String) |
Some (not all) Numeric Operations
Class | Float | Double |
| | |
Variables | MAX_VALUE | MAX_VALUE |
| MIN_VALUE | MIN_VALUE |
| NEGATIVE_INFINITY | NEGATIVE_INFINITY |
| NaN | NaN |
| POSITIVE_INFINITY | POSITIVE_INFINITY |
| | |
Constructors | Float(float) | Double(double) |
| Float(double) | Double(String) |
| Float(String) | |
| | |
Methods | doubleValue() | doubleValue() |
| equals(Object) | equals(Object) |
| intValue() | floatValue() |
| isInfinite() | intValue() |
| isNaN() | isInfinite() |
| longValue() | isNaN() |
| toString() | longValue() |
| valueOf(String) | toString() |
import java.util.Vector;
class SampleVector
{
public static void main( String args[] )
{
Vector growableList = new Vector( 2 );
String myName = "Roger";
for ( int k = 0; k < 5; k++ )
growableList.addElement( new Integer( k ) );
growableList.addElement( myName );
growableList.addElement( new SampleVector() );
growableList.setElementAt( "Hi", 2 );
System.out.println( growableList.toString() );
String convert = (String) growableList.elementAt( 2 );
growableList.removeElementAt( 5 );
System.out.println( growableList.indexOf( myName ) );
}
}
Output
[0, 1, Hi, 3, 4, Roger, SampleVector@5e3008a8]
-1
Some Vector Methods
addElement(Object) | indexOf(Object) | removeElement(Object) |
capacity() | insertElementAt(Object, int) | removeElementAt(int) |
clone() | isEmpty() | setElementAt(Object, int) |
contains(Object) | lastElement() | setsize(int) |
copyInto(Object[]) | lastIndexOf(Object) | size() |
elementAt(int) | lastIndexOf(Object, int) | toString() |
elements() | removeAllElements() | trimTosize() |
firstElement() | | |
Beware! Vector Size May Not Mean What You Think!
import java.util.Vector;
class DoesNotWork
{
public static void main( String args[] )
{
Vector empty = new Vector( 200 );
empty.setElementAt( "No one home", 2 );
}
}
Output
java.lang.ArrayIndexOutOfBoundsException: 2 >= 0
at java.util.Vector.setElementAt(Vector.java)
at DoesNotWork.main(All.java:8)
This Works with no Runtime Error
import java.util.Vector;
class ThisWorks
{
public static void main( String args[] )
{
Vector fillFirst = new Vector( 200 );
for ( int k = 0; k < 200; k++ )
fillFirst.addElement( null );
fillFirst.setElementAt( "Ok", 2 );
}
}
Arrays and Objects
Arrays are not objects
Objects can refer to arrays
import java.util.Vector;
class ArrayAndObject
{
public static void main( String args[] )
{
Vector test = new Vector( );
int[] grades = new int[25];
grades[10] = 4;
test.addElement( grades );
int[] recoveredGrades = ( int[] ) test.elementAt( 0 );
System.out.println( recoveredGrades[ 10 ] );
recoveredGrades[ 2 ] = 12;
System.out.println( grades[ 2 ] );
}
}
Output
4
12
"The Enumeration interface specifies a set of methods that may be used to
enumerate, or count through, a set of values. The enumeration is consumed by
use; its values may only be counted once.
For example, to print all elements of a Vector v: "
for (Enumeration e = v.elements() ; e.hasMoreElements() ;)
{
System.out.println(e.nextElement());
}
Enumeration Methods
hasMoreElements()
- Returns true if the enumeration contains more elements; false if its empty.
nextElement()
- Returns the next element of the enumeration.
import java.util.*;
class SampleVector
{
public static void main( String args[] )
{
Vector monthyOutput = new Vector( 2 );
Random dailyOutput = new Random();
for ( int k = 0; k < 5; k++ )
monthyOutput.addElement(
new Integer( dailyOutput.nextInt() ) );
Enumeration output = monthyOutput.elements();
while ( output.hasMoreElements() )
System.out.print( output.nextElement() + "\t" );
System.out.println( );
output = monthyOutput.elements();
int totalOutput = 0;
while ( output.hasMoreElements() )
{
Integer storedOutput = (Integer) output.nextElement();
totalOutput += storedOutput.intValue();
}
System.out.println( totalOutput );
}
}
import java.util.*;
class SampleStack
{
public static void main( String args[] )
{
Stack test = new Stack();
test.push( new Integer( 5 ) );
test.push( 5 ); //compile error
test.push( new Student() );
System.out.println( test.pop() );
Student fromStack = (Student) test.pop();
}
}
class Student
{
public String name;
}
Some Stack Methods
empty()
peek()
pop()
push(Object)
search(Object)
Maps keys to values.
Any object can be used as a key and/or value.
Object used as a key must implement hashCode() & equals()
Some Hashtable Methods
clear() | get(Object) | rehash() |
clone() | isEmpty() | remove(Object) |
contains(Object) | keys() | size() |
containsKey(Object) | put(Object, Object) | toString() |
elements() | | |
Hashtable Example
import java.util.*;
class Student { String[] courses; }
class SampleHash
{
public static void main( String args[] ) {
Student csPerson = new Student();
Hashtable sample = new Hashtable();
sample.put( "Roger", "Good Job" );
sample.put( "Andrew", "Better Job" );
sample.put( csPerson, new Integer( 12 ) );
Stack ofCards = new Stack();
sample.put( "Deck", ofCards );
String myPerformance = (String) sample.get( "Roger" );
Enumeration keys = sample.keys();
while ( keys.hasMoreElements() )
{
System.out.print( keys.nextElement() + "\t" );
}
System.out.println();
Enumeration elements = sample.elements();
while ( elements.hasMoreElements() )
{
System.out.print( elements.nextElement() + "\t" );
}
System.out.println();
}
}
Output
Andrew Student@5e300848 Roger Deck
Better Job 12 Good Job []
Random Constructors
Random()
Creates a new random number generator.
Random(long)
Creates a random number generator using a long as a seed.
import java.util.Random;
class SampleRandom
{
public static void main( String args[] )
{
Random data = new Random();
System.out.println( data.nextDouble() );
System.out.println( data.nextFloat() );
System.out.println( data.nextGaussian() );
System.out.println( data.nextLong() );
System.out.println( data.nextDouble() );
}
}
Output
0.941441
0.476748
-0.894882
-2651647369108839684
0.626033
Random Methods
nextDouble() | nextInt() |
nextFloat() | nextLong() |
nextGaussian() | setSeed(long) |
import java.util.*;
class Parse
{
public static void main( String args[] )
{
String message = "this is a test";
StringTokenizer parser = new StringTokenizer( message );
System.out.println( parser.countTokens() );
printTokens( parser );
message = "Hi,Mom;this.is a funny, message";
parser = new StringTokenizer( message, ",;." );
printTokens( parser );
parser = new StringTokenizer( message, ",;.", true );
printTokens( parser );
}
static void printTokens( StringTokenizer input)
{
while (input.hasMoreTokens())
{
System.out.println( input.nextToken() );
}
}
}
Output
4 | Hi | Hi |
this | Mom | , |
is | this | Mom |
a | is a funny | ; |
test | message | this |
| | . |
| | is a funny |
| | , |
| | message |
StringTokenizer Constructors
StringTokenizer(String, String, boolean)
- Constructs a StringTokenizer on the specified String, using the specified
delimiter set. If boolean is true, return delimiters with tokens.
StringTokenizer(String, String)
- Constructs a StringTokenizer on the specified String, using the specified
delimiter set.
StringTokenizer(String)
- Constructs a StringTokenizer on the specified String, using the default
delimiter set (which is " \t\n\r").
StringTokenizer Methods
countTokens() | nextElement() |
hasMoreElements() | nextToken() |
hasMoreTokens() | nextToken(String) |
If you really miss working with bits, this class is for you
BitSet Constructors
BitSet()
- Creates an empty set.
BitSet(int)
- Creates an empty set with the specified size.
BitSet Methods
and(BitSet) | or(BitSet) |
clear(int) | set(int) |
clone() | size() |
equals(Object) | toString() |
get(int) | xor(BitSet) |
hashCode() | |
clone()
- Creates a clone of the object.
equals(Object)
- Compares two Objects for equality.
finalize()
- Code to perform when this object is garbage collected.
getClass()
- Returns the Class of this Object.
hashCode()
- Returns a hashcode for this Object.
notify()
- Notifies a single waiting thread on a change in condition of another
thread.
notifyAll()
- Notifies all of the threads waiting for a condition to change.
toString()
- Returns a String that represents the value of this Object.
wait(long)
- Causes a thread to wait until it is notified or the specified timeout
expires.
wait(long, int)
- More accurate wait.
wait()
- Causes a thread to wait forever until it is notified.