Arrays copyOf Range And Fill

Copy, pad, slice, and fill primitive arrays with Arrays.copyOf, copyOfRange, and fill, keeping ranges half-open and copies independent.

JavaData Integrity

Code

snippet
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] source = {10, 20, 30, 40, 50};

        // copyOf:指定新长度,变长部分补 0
        int[] head = Arrays.copyOf(source, 3);
        int[] padded = Arrays.copyOf(source, 7);

        // copyOfRange:区间左闭右开 [from, to)
        int[] middle = Arrays.copyOfRange(source, 1, 5);

        System.out.println("head: " + Arrays.toString(head));
        System.out.println("padded: " + Arrays.toString(padded));
        System.out.println("middle: " + Arrays.toString(middle));

        int[] flags = new int[6];
        Arrays.fill(flags, -1);
        Arrays.fill(flags, 1, 5, 7); // 只填充下标 [1, 5)
        System.out.println("flags: " + Arrays.toString(flags));

        // 拷贝是独立的数组:改副本不影响原数组
        head[0] = 99;
        System.out.println("source[0]=" + source[0] + " head[0]=" + head[0]);
    }
}

What the code does

The working surface is the class Main and the function main — everything else is wiring.

Using it

The main signature reads public static void main(String[] args)

Running the file prints labeled results such as head:, padded:, middle: — each operation’s effect is visible in the output.

Key statements

int[] middle = Arrays.copyOfRange(source, 1, 5);
Arrays.fill(flags, 1, 5, 7); // 只填充下标 [1, 5)
System.out.println("flags: " + Arrays.toString(flags));
int[] padded = Arrays.copyOf(source, 7);

Interactive Tools for This Topic

FAQ

What does Arrays copyOf Range And Fill print when run?
Execute the whole file; each printed line is prefixed with a label like `head:`, `padded:`, `middle:`.