ravi
ravi

Reputation: 6328

How to initialize all the elements of an array to any specific value in java

In C and C++ we have the memset() function which can fulfill my wish. But in Java, how can I initialize all the elements to a specific value?

Whenever we write int[] array = new int[10], this simply initializes an array of size 10 having all elements set to 0, but I just want to initialize all elements to something other than 0 (say, -1).

Otherwise I have to put a for loop just after the initialization, which ranges from index 0 to index size − 1, and inside that loop assign each element to the desired value, like this:

int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
    array[i] = -1;
}

Am I going correct? Is there any other way to do this?

Upvotes: 141

Views: 313499

Answers (11)

Mohan
Mohan

Reputation: 1244

For Lists, you can use

Collections.fill(arrayList, "-")

Upvotes: 0

0xdeee
0xdeee

Reputation: 9

Arrays class in java.utils has a method for that.

Arrays.fill(your_array, value_to_fill);

Upvotes: 0

hd84335
hd84335

Reputation: 9903

Using Java 8, you can simply use ncopies of Collections class:

Object[] arrays = Collections.nCopies(size, object).stream().toArray();

In your case it will be:

Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.

Here is a detailed answer of a similar case of yours.

Upvotes: 1

Danation
Danation

Reputation: 793

You could do this if it's short:

int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

but that gets bad for more than just a few.

Easier would be a for loop:

  int[] myArray = new int[10];
  for (int i = 0; i < array.length; i++)
       myArray[i] = -1;

Edit: I also like the Arrays.fill() option other people have mentioned.

Upvotes: 3

Alexey
Alexey

Reputation: 9447

It is also possible with Java 8 streams:

int[] a = IntStream.generate(() -> value).limit(count).toArray();

Probably, not the most efficient way to do the job, however.

Upvotes: 8

Renuz
Renuz

Reputation: 1657

Evidently you can use Arrays.fill(), The way you have it done also works though.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

If it's a primitive type, you can use Arrays.fill():

Arrays.fill(array, -1);

[Incidentally, memset in C or C++ is only of any real use for arrays of char.]

Upvotes: 265

user973999
user973999

Reputation:

You can use Arrays.fill(array, -1).

Upvotes: 1

Sam Goldberg
Sam Goldberg

Reputation: 6801

Have you tried the Arrays.fill function?

Upvotes: 1

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

There's also

int[] array = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};

Upvotes: 31

Aravind Yarram
Aravind Yarram

Reputation: 80176

java.util.Arrays.fill()

Upvotes: 2

Related Questions