Detect implicit use of deprecated next() in foreach loop

12 views
Skip to first unread message

Michael Ernst

unread,
Apr 21, 2021, 12:06:44 PM4/21/21
to fastutil
Is there a way to detect that my code is doing unnecessary boxing by using next() implicitly in a foreach loop?

fastutil provides iterators in which methods like next() are deprecated.
Thus, if I use the method next() explicitly in my code, javac will warn me to use a different method such as nextInt() instead.
However, if I use a foreach loop, there is no explicit use of next() and no warning, with either of these constructs:

  foreach (Integer i : myIntList) { ... }

  foreach (int i : myIntList) { ... }

These constructs are unnecessarily inefficient because of extra boxing, and I would like to know where I have made this mistake.

                     Thanks,

                    -Mike

Sebastiano Vigna

unread,
Apr 21, 2021, 7:20:36 PM4/21/21
to fastutil
I know no solution. There's no deprecation that will work because the method used by foreach is correct, and not deprecable as it returns an IntIterator. The problem is that foreach know nothing about fastutil.

You should try to use whenever possible the foreach() method. The documentation is pretty clear about it:

----

Note that “for each” iteration must be avoided:

long t = 0; for(long x: s) t += x;

In the loop above, boxing and unboxing is happening (even if your IDE does not report it). In some cases, a solution is to use a type-specific forEach():

// Print all elements s.forEach(x -> System.out.println(x));

Or we can use fastutil's type-specific version of Java 8's streams:

long t = m.longStream().sum();

----
 
Reply all
Reply to author
Forward
0 new messages