SDSU CS 596 Client-Server Programming
More Vector

[To Lecture Notes Index]
San Diego State University -- This page last updated February 15, 1996
----------

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

----------