Which is better Java programming practice for looping up to an int value: a converted for-each loop

Posted by Arvanem on Stack Overflow See other posts from Stack Overflow or by Arvanem
Published on 2010-04-25T14:52:31Z Indexed on 2010/04/25 15:03 UTC
Read the original article Hit count: 366

Hi folks,

Given the need to loop up to an arbitrary int value, is it better programming practice to convert the value into an array and for-each the array, or just use a traditional for loop?

FYI, I am calculating the number of 5 and 6 results ("hits") in multiple throws of 6-sided dice. My arbitrary int value is the dicePool which represents the number of multiple throws.

As I understand it, there are two options:

  1. Convert the dicePool into an array and for-each the array:

    public int calcHits(int dicePool) {
       int[] dp = new int[dicePool];
       for (Integer a : dp) {
         // call throwDice method
       }
    }
    
  2. Use a traditional for loop.

    public int calcHits(int dicePool) {
       for (int i = 0; i < dicePool; i++) {
         // call throwDice method
       }
    }
    

I apologise for the poor presentation of the code above (for some reason the code button on the Ask Question page is not doing what it should).

My view is that option 1 is clumsy code and involves unnecessary creation of an array, even though the for-each loop is more efficient than the traditional for loop in Option 2.

Thanks in advance for any suggestions you might have.

© Stack Overflow or respective owner

Related posts about java

Related posts about foreach-loop