I'm working with Java 7, and I'm searching in the Guava API for a way to apply a function to an array without having to convert it to a Collection first. I'm willing to create my own class for such purpose, but I don't want to reinvent the wheel hehe.
So as a summary (in case you don't know exactly what I'm talking about), this is what I've found so far that you can do with Guava in order to apply a function to an array as I said:
Integer[] someNumbers = new Integer[]{1, 2, 3};
Integer[] returnedNumbers = Collections2.transform(Arrays.asList(someNumbers), squareNumberFunction).toArray(new Integer[0]);
assertThat(returnedNumbers).isEqualTo(new Integer[]{1, 4, 9});//Using AssertJ here
But I would like to be able to do something like this instead:
Integer[] someNumbers = new Integer[]{1, 2, 3};
Integer[] returnedNumbers = Arrays.transform(someNumbers, squareNumberFunction);
assertThat(returnedNumbers).isEqualTo(new Integer[]{1, 4, 9});
Ideally the functionality I'm talking about would be type-safe.
EDIT
For even further clarification of the problem:
It's not true that arrays are considerably faster than collections - some collections are just wrappers over arrays so you loose nothing but gets the best of both worlds.
Coming back to your case I think you can use Arrays.asList
(a list backed by your array) or ImmutableList
(if you don't need growing array) whatever suits you but don't use Arrays. The very first sign is that you have to write unnecessary code (your answer and more in future) which you'll have to maintain/tune in future, in my experience it's not worth it.
Java is a higher level language and such tiny optimizations should be better left to Java for all the good reasons but even after all this if you still have doubts I would suggest you to write a micro benchmark to validate your assumption.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With