Computer Science Canada

help with vector

Author:  SilverSprite [ Wed Jul 09, 2003 8:29 pm ]
Post subject:  help with vector

i need to create a vector of Jbuttons.. any ideas? the java api isnt helping me much Confused

Author:  rizzix [ Wed Jul 09, 2003 11:44 pm ]
Post subject: 

it is easy.

first import the java.util.Vector; class and the java.util.Iterator; class

code:

Vector vec = new Vector();
String str = "test a string object";
vec.add(str); // vectors can only add objects not primitives, so if u have to
                    // add an int u fist need to create an Integer object to
                    // encapsulate that value.

str = "another str object";
vec.add(str);
// and so on and so forth
//...

// here's how u get objects from vectors...
Iterator itr; //declaration of iterator can go in the declaration part of the
                 // for loop, but then we can't use this variable outside the scope
                 // of the for loop.

String str2;

for (itr = vec.iterator(); itr.hasNext(); str2 = (String) itr.next())
    System.out.println(str2);

//here's an alternative syntax..
itr = vec.iterator();
while(itr.hasNext())
    System.out.println((String) itr.next());



we cast the object returned by the vector through the iterator as the more specifice type because the next() method returns an object of type Object which is the root class of all classes.

hope that was helpfull Mr. Green


: