How to Use Arrays.fill to Fill an Array

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - How to Use Arrays.fill to Fill an Array

This Java example program shows how to use Arrays.fill to fill an array.

[edit] Java Source Code

  • Package: com.exampleshow.array
  • File: ArrayFillTest.java
package com.exampleshow.array;
 
/**
 * @author Code Panda Copyright (C) 2008 Java ExampleShow (http://java.exampleshow.com)
 * 
 *         This code is free software; you can redistribute it and/or modify it. However, this
 *         header must remain intact and unchanged. Additional information may be appended after
 *         this header. Publications based on this code must also include an appropriate reference.
 * 
 *         This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *         without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * 
 */
import java.util.Arrays;
import java.util.Date;
 
public class ArrayFillTest {
    public static void main(String args[]) {
	int array[] = new int[10];
	Arrays.fill(array, 10);
	for (int i = 0, n = array.length; i < n; i++) {
	    System.out.println(array[i]);
	}
	System.out.println();
	Arrays.fill(array, 3, 6, 5);
	for (int i = 0, n = array.length; i < n; i++) {
	    System.out.println(array[i]);
	}
	byte array2[] = new byte[10];
	Arrays.fill(array2, (byte) 4);
 
	System.out.println();
	Date array3[] = new Date[10];
	Date dataObject = new Date();
 
	try {
	    Arrays.fill(array3, dataObject);
	} catch (Exception e) {
	    e.printStackTrace();
	}
 
	dataObject.setYear(108);
	for (int i = 0, n = array3.length; i < n; i++) {
	    System.out.println(array3[i]);
	}
    }
}

[edit] What Result You Can Get

Run the program, you will get:

10
10
10
10
10
10
10
10
10
10

10
10
10
5
5
5
10
10
10
10

Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008
Fri Aug 15 08:43:23 PDT 2008

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools