SDSU 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

  1. References
    1. Classes by Type
    2. Classes by Package
    3. Containers
      1. Numeric Classes
      2. Vector
      3. Enumeration
      4. Vectors and Enumeration
      5. Stack
      6. Hashtable
    4. Some Useful Classes
      1. Random
      2. StringTokenizer
      3. BitSet
    5. Object

                                  Some Java Data Structures Slide # 1

References


Core Java, Chapter 9

On-Line Java API documentation
Reading

Core Java, Chapter 9

                                  Some Java Data Structures Slide # 2Listen Here!

Classes by Type

GENERAL
AppletDatagramSocketImageProducerRandomAccessFile
AppletContextDateIndexColorModelRectangle
AppletStubDebuggerCallbackInetAddressRunnable
AudioClipDialogInsetsRuntime
BitSetDictionaryIntegerRuntimeConstants
BooleanDimensionLabelScrollbar
BorderLayoutDirectColorModelLayoutManagerSecurityManager
ButtonDoubleListServerSocket
CanvasEnumerationLocalVariableSocket
CardLayoutEventLongSocketImpl
CharacterFieldMathSocketImplFactory
CheckboxFileMediaTrackerStack
CheckboxGroupFileDescriptorMemoryImageSourceStackFrame
CheckboxMenuItemFileDialogMenuString
ChoiceFilenameFilterMenuBarStringBuffer
ClassFilteredImageSourceMenuComponentStringTokenizer
ClassLoaderFloatMenuContainerSystem
CloneableFlowLayoutMenuItemTextArea
ColorFontNumberTextComponent
ColorModelFontMetricsObjectTextField
CompilerFrameObservableThread
ComponentGraphicsObserverThreadDeath
ConstantsGridBagConstraintsPanelThreadGroup
ContainerGridBagLayoutPixelGrabberThrowable
ContentHandlerGridLayoutPointToolkit
ContentHandlerFactoryHashtablePolygonURL
CropImageFilterImageProcessURLConnection
DataInputImageConsumerPropertiesURLEncoder
DataOutputImageFilterRGBImageFilterVector
DatagramPacketImageObserverRandomWindow


STREAMS
BufferedInputStreamInputStream
BufferedOutputStreamLineNumberInputStream
ByteArrayInputStreamOutputStreamPipedInputStream
ByteArrayOutputStreamPipedOutputStreamPrintStream
DataInputStreamPushbackInputStream
DataOutputStreamSequenceInputStreamStreamTokenizer
FileInputStreamStringBufferInputStream
FileOutputStreamURLStreamHandler
FilterInputStreamURLStreamHandlerFactory
FilterOutputStream

                                  Some Java Data Structures Slide # 3
PEERS
ButtonPeerFileDialogPeerMenuPeer
CanvasPeerFramePeerPanelPeer
CheckboxMenuItemPeerLabelPeerScrollbarPeer
CheckboxPeerListPeerTextAreaPeer
ChoicePeerMenuBarPeerTextComponentPeer
ComponentPeerMenuComponentPeerTextFieldPeer
ContainerPeerMenuItemPeerWindowPeer
DialogPeer


REMOTES

RemoteArrayRemoteBoolean
RemoteByteRemoteChar
RemoteClassRemoteDebugger
RemoteDouble
RemoteFieldRemoteFloatRemoteInt
RemoteLongRemoteObject
RemoteShortRemoteStackFrame
RemoteStackVariableRemoteString
RemoteThreadRemoteThreadGroup
RemoteValue
                                  Some Java Data Structures Slide # 4

Classes by Package

class java.applet
Applet
AppletContext
AppletStub
AudioClip


class java.awt
AWTErrorEventMenu
AWTExceptionFileDialogMenuBar
BorderLayoutFlowLayoutMenuComponent
ButtonFontMenuItem
CanvasFontMetricsPanel
CardLayoutFramePoint
CheckboxGraphicsPolygon
CheckboxGroupGridBagConstraintsRectangle
CheckboxMenuItemGridBagLayoutScrollbar
ChoiceGridLayoutTextArea
ColorImageTextComponent
ComponentInsetsTextField
ContainerLabelToolkit
DialogListWindow
DimensionMediaTracker
LayoutManagerMenuContainer


class java.awt.image
ColorModelIndexColorModel
CropImageFilterMemoryImageSource
DirectColorModelPixelGrabber
FilteredImageSourceRGBImageFilter
ImageFilterImageConsumer
ImageObserverImageProducer


                                  Some Java Data Structures Slide # 5
class java.io
BufferedInputStreamFileNotFoundExceptionPipedInputStream
BufferedOutputStreamFileOutputStreamPipedOutputStream
ByteArrayInputStreamFilterInputStreamPrintStream
ByteArrayOutputStreamFilterOutputStreamPushbackInputStream
DataInputStreamInputStreamRandomAccessFile
DataOutputStreamInterruptedIOExceptionSequenceInputStream
EOFExceptionIOExceptionStreamTokenizer
FileLineNumberInputStreamStringBufferInputStream
FileDescriptorOutputStreamUTFDataFormatException
FileInputStream
DataInputDataOutputFilenameFilter


class java.lang
AbstractMethodErrorIllegalMonitorStateExceptionOutOfMemoryError
ArithmeticExceptionIllegalThreadStateExceptionProcess
ArrayIndexOutOfBoundsExceptionIncompatibleClassChangeErrorRuntimeException
ArrayStoreExceptionIndexOutOfBoundsExceptionSecurityException
BooleanInstantiationErrorSecurityManager
CharacterInstantiationExceptionStackOverflowError
ClassIntegerString
ClassCastExceptionInternalErrorStringBuffer
ClassCircularityErrorInterruptedExceptionStringIndexOutOfBoundsException
ClassFormatErrorLinkageErrorSystem
ClassLoaderLongThread
ClassNotFoundExceptionMathThreadDeath
CloneNotSupportedExceptionNegativeArraysizeExceptionThreadGroup
CompilerNoClassDefFoundErrorThrowable
DoubleNoSuchFieldErrorUnknownError
ErrorNoSuchMethodErrorUnsatisfiedLinkError
ExceptionNoSuchMethodExceptionVerifyError
FloatNullPointerExceptionVirtualMachineError
IllegalAccessErrorNumber
IllegalAccessExceptionNumberFormatException
IllegalArgumentExceptionObject
CloneableRunnable

                                  Some Java Data Structures Slide # 6
class java.net
ContentHandlerServerSocketUnknownServiceException
DatagramPacketSocketURL
DatagramSocketSocketExceptionURLConnection
InetAddressSocketImplURLEncoder
MalformedURLExceptionUnknownHostExceptionURLStreamHandler
ProtocolException
ContentHandlerFactorySocketImplFactoryURLStreamHandlerFactory


class java.util
BitSetHashtableRandom
DateNoSuchElementExceptionStack
DictionaryObservableStringTokenizer
EmptyStackExceptionPropertiesVector
EnumerationObserver


class sun.tools.debug
FieldRemoteDoubleRemoteStackFrame
LocalVariableRemoteFieldRemoteStackVariable
RemoteArrayRemoteFloatRemoteString
RemoteBooleanRemoteIntRemoteThread
RemoteByteRemoteLongRemoteThreadGroup
RemoteCharRemoteObjectRemoteValue
RemoteClassRemoteShortStackFrame
RemoteDebugger
DebuggerCallbackConstantsRuntimeConstants

                                  Some Java Data Structures Slide # 7Listen Here!

Containers

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
}



                                  Some Java Data Structures Slide # 8Listen 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;

   }
}


                                  Some Java Data Structures Slide # 9Listen Here!
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();

   }
}

                                  Some Java Data Structures Slide # 10

Numeric Classes


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

                                  Some Java Data Structures Slide # 11Listen Here!
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 Java Data Structures Slide # 12Listen Here!
Some (not all) Numeric Operations
ClassIntegerLong
VariablesMAX_VALUEMAX_VALUE
MIN_VALUEMIN_VALUE
ConstructorsInteger(int)Long(long)
Integer(String)Long(String)
MethodsdoubleValue()doubleValue()
equals(Object)equals(Object)
floatValue()floatValue()
intValue()intValue()
longValue()longValue()
toString()toString()
valueOf(String)valueOf(String)

                                  Some Java Data Structures Slide # 13
Some (not all) Numeric Operations
ClassFloatDouble
VariablesMAX_VALUEMAX_VALUE
MIN_VALUEMIN_VALUE
NEGATIVE_INFINITYNEGATIVE_INFINITY
NaNNaN
POSITIVE_INFINITYPOSITIVE_INFINITY
ConstructorsFloat(float)Double(double)
Float(double)Double(String)
Float(String)
MethodsdoubleValue()doubleValue()
equals(Object)equals(Object)
intValue()floatValue()
isInfinite()intValue()
isNaN()isInfinite()
longValue()isNaN()
toString()longValue()
valueOf(String)toString()


                                  Some Java Data Structures Slide # 14Listen Here!

Vector

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

                                  Some Java Data Structures Slide # 15Listen Here!
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 );
   }
}

                                  Some Java Data Structures Slide # 16Listen Here!
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
                                  Some Java Data Structures Slide # 17Listen Here!

Enumeration


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


                                  Some Java Data Structures Slide # 18Listen Here!

Vectors and 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   );
   }
}

                                  Some Java Data Structures Slide # 19Listen Here!

Stack

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) 

                                  Some Java Data Structures Slide # 20Listen Here!

Hashtable


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

                                  Some Java Data Structures Slide # 21Listen Here!
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 []
                                  Some Java Data Structures Slide # 22

Some Useful Classes


                                  Some Java Data Structures Slide # 23

Random

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)

                                  Some Java Data Structures Slide # 24Listen Here!

StringTokenizer

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
4HiHi
thisMom,
isthisMom
ais a funny;
test messagethis
.
is a funny
,
message

                                  Some Java Data Structures Slide # 25Listen Here!
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)

                                  Some Java Data Structures Slide # 26Listen Here!

BitSet


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

                                  Some Java Data Structures Slide # 27

Object


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.


----------