This is my first activity here, I hope I behave correctly! My problem: I am trying to write a collection of functions (static methods in a class) that accept one or several Iterable<Integer>
and obtains the primitiveIterator.ofInt, providing it to another function that constructs yet another iterator (i.e. the functions are meant to compose iterators in various ways).
Here is a simple example of what I have in mind:
public static FilterIteratorInt filtor(Iterable<Integer> iter, IntPredicate filter)
{
return new FilterIteratorInt((PrimitiveIterator.OfInt)iter.iterator(),filter);
}
To me, it is not quite clear whether this can work at all, because the iterator
returned by the Iterable<Integer>
Object might not be of type PrimitiveIterator.OfInt
.
In order to overcome this potential difficulty, I have been looking for a solution, which might either be an Interface like e.g. PrimitiveIterable.OfInt
or any other way to find out whether the iterator is in fact primitive. I have been searching for quite a while, but while usually just browsing answers nearly all of my question, this time I had to register here to ask that question directly.
This construction is meant to avoid boxing/unboxing orgies, since I want the new iterators to be reasonably fast.
So here are three questions:
- Is there a way to find out whether the iterator obtained from an iterable is in fact a primitive iterator (such that the function can distinguish and act accordingly) or is there another way to obtain one?
- Is it possibly useless to try to improve performance this way? I.e. will (JIT or Java)compilers optimize this anyway, or is boxing/unboxing unavoidable anyway under the hood? Here I hope to learn something.
- Can somebody show me a different and better solution that could serve the same purpose (i.e. composition of primitive iterators, or of any iterators, while we are at it)?
Update: Due to Holgers answer, it boils down to the following question nr. 4: If next()
is called on a PrimitiveInteger.OfInt
, will this invoke the nextInt()
method, or in other words: Will this automatically end up returning a pure int
? Or will it still cause a boxing and unboxing sequence?
From the answer below I assume the latter, and this would mean it is definitely better to deal with nextInt()
explicitly.
Assuming that this is correct (please tell me if I am wrong), I have used the instanceof
method below and explicitly wrap if required.