Fastest way to set all values of an array?

后端 未结 14 2318
悲哀的现实
悲哀的现实 2020-12-04 17:47

I have a char [], and I want to set the value of every index to the same char value.
There is the obvious way to do it (iteration):

<         


        
14条回答
  •  余生分开走
    2020-12-04 17:58

    You could use arraycopy but it depends on whether you can predefine the source array, - do you need a different character fill each time, or are you filling arrays repeatedly with the same char?

    Clearly the length of the fill matters - either you need a source that is bigger than all possible destinations, or you need a loop to repeatedly arraycopy a chunk of data until the destination is full.

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

提交回复
热议问题