Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise an array in Java with a constant value efficiently

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.

like image 645
kon psych Avatar asked Feb 22 '23 14:02

kon psych


1 Answers

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.

like image 115
biziclop Avatar answered Apr 13 '23 00:04

biziclop