本文介绍了设置数组所有值的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 char []
,我想将每个索引的值设置为相同的 char
值.
有一个显而易见的方法(迭代):
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):
char f = '+';
char [] c = new char [50];
for(int i = 0; i < c.length; i++){
c[i] = f;
}
但我想知道是否有一种方法可以利用 System.arraycopy
或等效的东西来绕过迭代的需要.有没有办法做到这一点?
But I was wondering if there's a way that I can utilize System.arraycopy
or something equivalent that would bypass the need to iterate. Is there a way to do that?
来自 Arrays.java
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;
}
这是完全相同的过程,这表明可能没有更好的方法来做到这一点.
+1 给所有建议 fill
的人 - 你们都是对的,谢谢.
This is exactly the same process, which shows that there might not be a better way to do this.
+1 to everyone who suggested fill
anyway - you're all correct and thank you.
推荐答案
Try Arrays.fill(c, f)
: 数组 javadoc
这篇关于设置数组所有值的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!