CS 596 Client-Server Programming
Classes: Containers
[To Lecture Notes Index]
San Diego State University -- This page last updated February 6, 1996
Contents of Classes: Containers Lecture
- Containers
- The Container Problem
- Vector
- Enumeration
- Vectors and Enumeration
- Stack
- Hashtable
- Some Useful Classes
- Random
- StringTokenizer
- BitSet
- Object
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
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
}
}
Smalltalk
solution: numbers are objects
Java solution
- int, float, long, etc. are not object due to C/C++
-
- Integer, Float, Double, Long are wrapper classes
class UseLinkedListNode
{
public static void main( String args[] )
{
LinkedListNode aNumNode = new LinkedListNode();
aNumNode.theData = new Integer( 5 );
int result = ((Integer) aNumNode.theData).intValue();
}
}
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() | | |
"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();
for ( ; output.hasMoreElements() ; )
System.out.print( output.nextElement() + "\t" );
System.out.println( );
output = monthyOutput.elements();
int totalOutput = 0;
for ( ; 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() | | |
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.