rtheunissen rtheunissen - 1 year ago 68
Java Question

Fastest way to set all values of an array?

I have a

char []
, and I want to set the value of every index to the same

There is the obvious way to do it (iteration):

char f = '+';
char [] c = new char [50];
for(int i = 0; i < c.length; i++){
c[i] = f;

But I was wondering if there's a way that I can utilize
or something equivalent that would bypass the need to iterate. Is there a way to do that?


public static void fill(char[] a, int fromIndex, int toIndex, char val) {
rangeCheck(a.length, fromIndex, toIndex);
for (int i = fromIndex; i < toIndex; i++)
a[i] = val;

This is exactly the same process, which shows that there might not be a better way to do this.

+1 to everyone who suggested
anyway - you're all correct and thank you.

Answer Source

Try Arrays.fill(c, f) : Arrays javadoc

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download