Calling next on an Iterator once vs multiple times

后端 未结 3 964
南方客
南方客 2020-12-12 00:51

Why this first version of the code does not work

          // returns the longest string in the list (does not work!)

         public static String longest         


        
3条回答
  •  时光取名叫无心
    2020-12-12 01:28

    Count the number of times next() is called in the first snipped compared to the second:

    while (itr.hasNext()) {
        if (itr.next().length() > longest.length()) {
            ^^^^^^^^^^
            longest = itr.next();
                      ^^^^^^^^^^
        }
    }
    

    compared to

    while (itr.hasNext()) {
        String current = itr.next();
                         ^^^^^^^^^^
        if (current.length() > longest.length()) {
            longest = current;
        }
    }
    

    Every time you call itr.next(), you advance the iterator another token. So in the first snippet, you only store/compare every other token, while in the second snippet you store/compare the same token.

提交回复
热议问题