Java Arraylist printing every other number in a list

Go To StackoverFlow.com

0

This is my code for printing the random numbers in an arraylist:

public void printList()
{
    System.out.println("The numbers on the list: ") ;
    for (int i = 0 ; i < aList.size() ; i++)
    {
        System.out.print( aList.get(i) + "  ") ;
    }
    System.out.println("\n") ;                
}

How would I print every other number of this same list? By using a do-while loop?

2012-04-04 19:49
by Nicole
instead of i++ do i += - ControlAltDel 2012-04-04 19:52


2

Put additional if statement inside your for block which would check for parity: if (i % 2 == 0) { System.out.print(... }

2012-04-04 19:51
by ahanin


2

Above approach is ineffecient. Just increment the index by 2

public void print()
{
    System.out.println("The numbers on the list: ") ;
    for (int i = 0 ; i < aList.size() ; i+=2)
    {
        System.out.print( aList.get(i) + "  ") ;
    }
    System.out.println();                
}
2012-04-04 19:54
by horbags
Both are inefficient with LinkedList. Prefer iteration over random element access and separate counter:

public void print() { System.out.println("The numbers on the list: ") ; int i = 0; for (Object o : aList) { if (i % 2 == 0) { System.out.print( o + " ") ; } i++; } System.out.println();
- ahanin 2012-04-04 20:01

Didn't they ask about ArrayList? Or did I miss something - Joey 2012-04-04 20:55
@Chris Edit: This will cause an outOfBoundsException if aList.size() is odd. Not on my Java! Can you write me an example - Ishtar 2012-04-04 21:00
@Joey Yes, they did, but it's still good to know how usage of different kinds of lists differ - ahanin 2012-04-05 07:58
Ads