Click to See Complete Forum and Search --> : are there any 2-d vectors?


Monika
September 20th, 2000, 06:01 AM
Hi,
In java.util.Vector , one can only have one dimension, is there a method of having two dimensional methods.
Thanks in advance
Monika

Splatt
September 20th, 2000, 12:17 PM
I've never tried this, but why not use a Vector of Vectors? Something along the lines of:

Vector mainVector = new Vector();
mainVector.addElement(new Vector());
mainVector.addElement(new Vector());




You could explicitly set the size of the vectors when you create them, if need be.

"There's nothing more dangerous than a resourceful idiot." ---Dilbert

Monika
September 20th, 2000, 11:35 PM
Hi,
Thanks a lot for your reply. But vector of vectors won't store something like
a[0][0]="hello";
a[0][1]="index1";

Phill
September 21st, 2000, 12:22 AM
Hi
You can do it like this:


import java.util.*;

class DoubleV{

public static void main(String[] args){
Vector outside = new Vector();
Vector one = new Vector();
Vector two = new Vector();
one.add("Im the first Object inside the first Vector(one) inside the outside Vector");
one.add("Im the second Object inside the first Vector(one) inside the outside Vector");
two.add("Im the first Object inside the second Vector(two) inside the outside Vector");
two.add("Im the second Object inside the second Vector(two) inside the outside Vector");
outside.add(one);
outside.add(two);
for(int i = 0; i < outside.size(); i++){
Vector v = (Vector)outside.elementAt(i);//cast back to Vector
for(int j = 0; j< v.size(); j++)
System.out.println((String)v.elementAt(j));//cast back to String
}//end outside loop
}//end main
}



You will have to cast back to the original type
that you put into the Vector, in this case
we put a Vector inside another Vector so
we have to cast back to a Vector when we retrieve
the element. The String also has to be cast back.
The reason that we have to cast back is because the elementAt(int index) method
returns an Object.
Hope this helps
Phill