Strange behaviour when looping through ArrayList
I am reading in a file of account numbers from a text file. The file is has one entry per line:
723591876
324365431
642394762
769709909
154200970
I am the adding the account numbers to an array list then printing them out. The problem that is happening, is that in the for loop in the code below, it seems to be skipping every other entry and I have no idea why this is happening.
ArrayList theList =new ArrayList();
bufferedReader =new BufferedReader (new FileReader(inputFile));
while ((inputLine = bufferedReader.readLine()) !=null)
{
theList.add(inputLine);
}
for (int i = 0; i < theList.size(); i++)
{
String accountNumber = theList.get(i).toString().trim();
System.out.println("The account number is "+accountNumber);
theList.remove(i);
}
The console prints out:
The account number is 723591876
The account number is 642394762
The account number is 154200970
And if I enter an integer for theList.size(), which is more than half the size of the list, and ArrayIndexOutOfBoundsExceptin is thrown.
Any thoughts?
[1535 byte] By [
drakestera] at [2007-11-27 10:56:36]

that is correct, I need to remove the value after displaying it. Using iterator:
for (Iterator iter = theList.iterator(); iter.hasNext(); )
{
accountNumber = (String)iter.next();
System.out.println("The account number is "+accountNumber)
iter.remove();
}
How would I assign an integer value to the iterator so that it would only iterate through say 5 times?
> that is correct, I need to remove the value after
> displaying it. Using iterator:
>
> > for (Iterator iter = theList.iterator();
> iter.hasNext(); )
> {
>accountNumber = (String)iter.next();
> System.out.println("The account number is
> "+accountNumber)
>iter.remove();
>
>
>
> How would I assign an integer value to the iterator
> so that it would only iterate through say 5 times?
Why after 5 times? Your original code doesn't do that, it works off the size of the collection. The iterator will stop on it's own once it's been through the entire collection
> So something like this?
>
> [code]
> int count = 0;
> for (Iterator iter = theList.iterator();
> iter.hasNext(); )
> {
>count++
> accountNumber = (String)iter.next();
> System.out.println("The account number is
> "+accountNumber)
> iter.remove();
> if count == 5
>break;
> /code]
Something like that, yeh. Test it first though. But why after 5 times?
If you have not already found your solution, you can use this -
for (int i = theList.size() -1 ; i >= 0; i--)
{
String accountNumber = theList.get(i).toString().trim();
System.out.println("The account number is "+accountNumber);
theList.remove(i);
}
The elements are now removed, but in reverse order....