Originally posted by pascal betz:
Hi
first: you might want to look at the java.util.List and (one of the implementations java.util.ArrayList); unless required you should use these classes instead of Vector (Vector is synchronized, ArrayList is not. Butboth iomplement the List itnerface).
But your problem still stays :-)
Iterating over a List is possible in two ways:
- use the index
- use the iterator
if you check out the API doc of List you will find the methods to get elements out of a List using the index of the item.
also in the API you will find the Iterator interface which can also be used to iterate over a List.
btw: in your example code there is just one element in your Vector: a String[] (and i assume you want to have two items beeing the two names)
lets see if this gets you further....
pascal
Thank you Pascal and Svend
I tried using the ArrayList, it worked fine, but I am not sure why I put the line Object names = (Object) iter.next(); in the for loop. It sort of popped out, and I decided to put Object and the code worked, please explain.
And I also did the vector one, it also works but throws an exception after printing the contents. please help.
Check code for Array List:
***************************************************************************
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test2 {
private String name1 = "kim";
private String name2 = "Mary";
public Test2(){
ArrayList array = new ArrayList();
array.add(name1);
array.add(name2);
for (Iterator iter = array.iterator(); iter.hasNext()
{
Object names = (Object) iter.next();
System.out.println(names);
}
}
public static void main( String[ ] args ){
new Test2();
}
}
*************************************************************************
Check the coe for Vector:
import java.util.Vector;
public class Test{
private String name1 = "kim";
private String name2 = "Mary";
private Vector vec ;
public Test(){
vec = new Vector();
vec.addElement(name1);
vec.addElement(name2);
for(int i=0;i <=vec.size();i++){
System.out.println(vec.elementAt(i));
}
}
public static void main( String[ ] args ){
new Test();
}
}
throws this exception:
java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at Test.<init>(Test.java:15)
at Test.main(Test.java:19)
kim
Mary
Exception in thread "main"