1

I understand how iteration work but may be I need more knowledge about it. Can any one please show me the main difference between these two statements:

while (scanner.hasNext()) {
        tokenizer = new StringTokenizer(scanner.nextLine());
        numberOfItems = Integer.parseInt(tokenizer.nextToken());
        int[] numbers = new int[numberOfItems];
        for (int i:numbers) {
            numbers[i] = Integer.parseInt(tokenizer.nextToken());
        }
        System.out.println(isJolly(numbers));
    }

while (scanner.hasNext()) {
        tokenizer = new StringTokenizer(scanner.nextLine());
        numberOfItems = Integer.parseInt(tokenizer.nextToken());
        int[] numbers = new int[numberOfItems];
        for (int i = 0; i < numberOfItems; i++) {
            numbers[i] = Integer.parseInt(tokenizer.nextToken());
        }
        System.out.println(isJolly(numbers));
    }

why these giving me 2 different output?

3
  • Primitive arrays don't use an Iterator object. For arrays, the enhanced for loop is syntactic sugar. See Effective Java, Item 46. Commented Sep 30, 2015 at 0:09
  • so you are saying I ca not use Iterator with array?but I used before and it gave me correct output. Commented Sep 30, 2015 at 0:13
  • No, there literally is no Iterator. :) int[] nums can't spawn you an Iterator. You used the enhanced for loop. Commented Sep 30, 2015 at 0:16

1 Answer 1

1

You have created empty array (array filled with zeroes).

    int[] numbers = new int[numberOfItems];

In case of

 for ( int i = 0; i < numbers.length; i++ ) ...

i starts from 0 and on each iteration it is incremented (i++). Iterations are finished when i became equals or more than numbers.length (aka numberOfItems). So sequence of i values is 0,1,2,3,4,5,...

In case of

for (int i:numbers) { 

You iterate on each value taken from array and you will get sequence of zeroes ( 0,0,0,0,0, ...).

And yours number[i] = will update only the number[0] element of resulting array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.