For Programmers: Free Programming Magazines  


Home > Archive > Java Help > January 2006 > List iterators question









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author List iterators question
Oxnard

2006-01-27, 9:57 pm

Here's a real simple Iterator example done in 1.4

public static void main(String[] args){
List list = new ArrayList();
String[] sa = new String[2];
// put some stuff in the list
for(int i = 0;i < 10; i++){
sa[0] = " this is sa[0] list position " + i + " ";
sa[1] = " this is sa[1] list position " + i + " ";
list.add(sa);
}
System.out.println("list has " + list.size() + " elements");
// iterate through the list
for(Iterator it=list.iterator(); it.hasNext();){
String[] saw =(String[]) it.next();
System.out.println(saw[0] + saw[1]);
}
}

When I run this I get:

list has 10 elements
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9
this is sa[0] list position 9 this is sa[1] list position 9

What I am not understanding is why I am not seeing:
this is sa[0] list position 0 this is sa[1] list position 0
this is sa[0] list position 1 this is sa[1] list position 1
this is sa[0] list position 2 this is sa[1] list position 2
this is sa[0] list position 3 this is sa[1] list position 3
this is sa[0] list position 4 this is sa[1] list position 4
this is sa[0] list position 5 this is sa[1] list position 5
this is sa[0] list position 6 this is sa[1] list position 6
this is sa[0] list position 7 this is sa[1] list position 7
this is sa[0] list position 8 this is sa[1] list position 8
this is sa[0] list position 9 this is sa[1] list position 9

In the examples I have seen it infers that the Collection.add(Obj) appends
to the list. And that an Interator starts at position 0 and increases. What
am I missing here?

thanks


opalpa@gmail.com opalinski from opalpaweb

2006-01-28, 3:57 am

The list contains ten refernces to the same array.

If you want to see the former put " String[] sa = new String[2]; " into
population loop.


Opalinski
opalpa@gmail.com
http://www.geocities.com/opalpaweb/

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com