SDSU CS 535: Object-Oriented Programming & Design
Fall Semester, 1997
Doc 7, Some Basic Java API

To Lecture Notes Index
San Diego State University -- This page last updated 23-Sep-97

Contents of Doc 7, Some Basic Java API

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

References


The Java Programming Language, Chapter 12

On-Line Java API documentation



Doc 7, Some Basic Java API Slide # 1Listen 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
}



Doc 7, Some Basic Java API Slide # 2Listen 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;

   }
}


Doc 7, Some Basic Java API Slide # 3
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();

   }
}

Doc 7, Some Basic Java API Slide # 4Listen Here!

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


Doc 7, Some Basic Java API Slide # 5Listen 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  );
   }
}

Doc 7, Some Basic Java API Slide # 6
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)


Doc 7, Some Basic Java API Slide # 7Listen 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

Doc 7, Some Basic Java API Slide # 8Listen 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 );
   }
}

Doc 7, Some Basic Java API Slide # 9Listen 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

Doc 7, Some Basic Java API Slide # 10Listen 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.


Doc 7, Some Basic Java API Slide # 11Listen 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   );
   }
}

Doc 7, Some Basic Java API Slide # 12

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) 

Doc 7, Some Basic Java API Slide # 13

Hashtable


Maps keys to values.

Any object can be used as a key and/or value.

The object used as a key must implement hashCode() & equals()

All objects have default hashCode() & equals() methods

Some Hashtable Methods
clear()get(Object)rehash()
clone()isEmpty()remove(Object)
contains(Object)keys()size()
containsKey(Object)put(Object, Object)toString()
elements()


Doc 7, Some Basic Java API Slide # 14
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
Student@3bb6e2   Andrew   Roger   Deck   
12   Better Job   Good Job   []

Doc 7, Some Basic Java API Slide # 15

Some Useful Classes


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

Doc 7, Some Basic Java API Slide # 16

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


Doc 7, Some Basic Java API Slide # 17
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)


Doc 7, Some Basic Java API Slide # 18

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


Doc 7, Some Basic Java API Slide # 19

Object


All classes have the class Object as an ancestor

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()
Causes a thread to wait forever until it is notified.


Doc 7, Some Basic Java API Slide # 20

Some Useful SDSU Library Classes

Table - a two dimensional array
import sdsu.util.Table;

class TableExample
   {
   public static void main( String args[] ) throws 
                                    ConversionException
      {
      int rows = 2;
      int columns = 2;
      Table chart = new Table( rows, columns );
      
      chart.setElementAt( "Sandra", 0, 0 );
      chart.setElementAt( "John", 0, 1 );
      chart.setElementAt( "Jose", 1, 0 );
      chart.setElementAt( "Roger", 1, 1 );
      
      System.out.println( chart.rowAt( 0 ) );
      System.out.println( chart.columnAt( 0 ) );
      System.out.println( chart.elementAt( 0, 0 ) );
      
      String flattened =  chart.toString();
      
      Table recoveredChart = new Table();
      recoveredChart.fromString( flattened );
      System.out.println( recoveredChart );
      } 
   }
Output
[Sandra, John]
[Sandra, Jose]
Sandra
Sandra,John;
Jose,Roger

Doc 7, Some Basic Java API Slide # 21
SortedList
import  sdsu.util.SortedList;

class Sorting
   {
   public static void main( String args[] ) 
      {
      SortedList names = SortedList.stringSorter();

      names.addElement( "Roger");
      names.addElement( "Leopoldo");
      names.addElement( "Adam");

      System.out.println( names.elementAt( 1 ) );

      System.out.println( names );
      
      names = (SortedList) names.reversed();
      System.out.println( names );
      } 
   }
Output
Leopoldo
Adam,Leopoldo,Roger
Roger,Leopoldo,Adam


visitors since 23-Sep-97