`

Arrays.fill()填充方法

阅读更多
Arrays.fill()功能很有限,只能用同一个值填充各个位置,他有两个比较典型的方法:
[size=medium]
public static void fill(boolean[] a, boolean val)
public static void fill(boolean[] a, int fromIndex, int toIndex,boolean val)
[/size]
第一个方法是把数组中所有的元素用val元素填充
第二个是把指定位置的元素用val填充,填充的位置包括fromIndex,不包括toIndex
index下标是从0开始

其实第一个方法是调用第二个方法的实现:
[size=medium]
public static void fill(boolean[] a, boolean val) {
        fill(a, 0, a.length, val);
    }

填充的实现方法也比较简单,就是一个for循环赋值
[/size]
[size=medium]
for (int i=fromIndex; i<toIndex; i++)
            a[i] = val;
}
[/size]
[size=medium]
package com.liuc.test.think.chapter16;

import java.util.Arrays;

public class FillingArrays {

	public static void main(String[] args) {
		int size=6;
		boolean[] a=new boolean[size];
		Arrays.fill(a, true);
		System.out.println(Arrays.toString(a));
		Arrays.fill(a, 1, 5, false);
		System.out.println(Arrays.toString(a));
	}

}

[/size]
输出结果:
[true, true, true, true, true, true]
[true, false, false, false, false, true]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics