5

Is there a way to initialise an array of integers (or possibly any array) to a constant value other than zero (or null) which are the defaults, without a for loop?

Ideally I am looking for a function like "ones" in matlab, which is not only neater but also more efficient.

1
  • 2
    Such methods almost always use loops. A reason it could be faster in Matlab is that its an interpreted language whereas Java can be compiled to native code. Ironically, some loops in java can be so heavily optimised they are faster than using native calls. e.g. a loop to copy long[] can be faster using a loop than using System.arrayCopy Commented Feb 5, 2012 at 15:43

1 Answer 1

9

Arrays.fill() is the method you're after. (Although internally it still uses a for loop, so unlike System.arrayCopy(), it isn't any faster.)

P.s.: Arrays, and its collection-based counterpart Collections are two extremely useful classes in general.

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

5 Comments

It may be faster in some implementations since the JITC knows it can bypass bounds checks.
It may be, but I don't know of any JIT implementations out there that treat the same code in a different way just because it's in `java.util. Do you know a specific JIT that does this?
Well, I once worked on a JITC that did so, and I think the more advanced Sun/Oracle JITCs do something similar, based on indirect evidence.
Many low-level routines in java. packages are intrinsified by the JIT, so that the "reference" implementation you see in the JDK source may never be executed. You can check the list of intrinsics here (look for Here are all the intrinsics). It doesn't seem to include Arrays.fill currently, but does include other methods from Arrays.
Thanks, that's useful knowledge.

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.