$show=/label

How To Set All values of Array To Same Value In Faster Way?

SHARE:

A quick and fastest way to fill the array with the same value. Example program to create an array with n copies of the same value/object Arrays.fill()

1. Overview

In this article, You will learn how to set or fill the all values of the array with a single value in a faster way. This is quite interesting to do but very easy.

In the previous article, I have shown how to create and initialize the array with values.

And also will show the example program to create an array with n copies of the same value/object using Arrays.fill() method.

How To Set All values of Array To Same Value In Faster Way?


2. How To Set All Values Of Array To Same Value

First, Let us write a simple code that creates an int array and fills with the given value.

package com.javaprogramto.arrays.fill;

public class FillArrayExampleCustom {

    public static void main(String[] args) {

        System.out.println("Array 1");        int[] array1 = fillArray(5, 10);
        printArray(array1);

        System.out.println("Array 2"); int[] array2 = fillArray(10, 25); printArray(array2); } private static int[] fillArray(int size, int valueToBeFilled){ // Creating an array int[] intArray = new int[size]; // setting the value to each index in the array for(int i =0;i<intArray.length; i++){ intArray[i] = valueToBeFilled; } return intArray; } private static void printArray(int[] array){ System.out.println("\n"); // printing the array for (int i = 0;i< array.length;i++){ System.out.print(" "+array[i] ); } } }
Output:
Array 1
10 10 10 10 10

Array 2
25 25 25 25 25 25 25 25 25 25
As you see the output, it just assigned the given value to each index by running a simple for loop.

3. Using Arrays.fill() Method


The above method works only for the primitive integer array. For each type, a new method should be created manually.

It is a bit painful to do. For such cases, java Arrays class provides several utility methods to make developer life easy.

Arrays.fill() method takes different types of arguments and fills the whole array with the same value.

fill() method is an overloaded method with all primitive types. Below is the syntax for the int[] array and all other methods follow the same.
public static void fill(int[] a, int val)

public static void fill(int[] a,
        int fromIndex,
        int toIndex,
        int val)
		
		
And also these fill() method works with start index and end index for setting the values. The remaining values do not change.
package com.javaprogramto.arrays.fill;

import java.util.Arrays;

public class ArraysFillExample {

    public static void main(String[] args) {

        int[] array1 = new int[5];
        // filling int values
        Arrays.fill(array1, 9);
        System.out.println(Arrays.toString(array1));

        int[] array2 = new int[10];
        // filling int values from index 3 to 7
        Arrays.fill(array2, 3, 7, 9);
        System.out.println(Arrays.toString(array2));

        boolean[] array3 = new boolean[10];
        // filling boolean values
        Arrays.fill(array3, true);
        System.out.println(Arrays.toString(array3));

        boolean[] array4 = new boolean[10];
        // filling int values from index 5 to 9
        Arrays.fill(array4, 5,9,true);
        System.out.println(Arrays.toString(array4));

        float[] array5 = new float[10];
        // filling float values
        Arrays.fill(array5, 55.5f);
        System.out.println(Arrays.toString(array5));

        float[] array6 = new float[10];
        // filling int values from index 2 to 7
        Arrays.fill(array6, 2,7,77.7f);
        System.out.println(Arrays.toString(array6));

    }
}

	
Output:
[9, 9, 9, 9, 9]
[0, 0, 0, 9, 9, 9, 9, 0, 0, 0]
[true, true, true, true, true, true, true, true, true, true]
[false, false, false, false, false, true, true, true, true, false]
[55.5, 55.5, 55.5, 55.5, 55.5, 55.5, 55.5, 55.5, 55.5, 55.5]
[0.0, 0.0, 77.7, 77.7, 77.7, 77.7, 77.7, 0.0, 0.0, 0.0]

4. Arrays.fill() Method Internals


Look at the below fill() method internal code that runs a simple for loop to set values.

Both our own custom logic and Arrays.fill() method works in same in terms of performance and same fast.
public static void fill(char[] a, char val) {
        for (int i = 0, len = a.length; i < len; i++)
            a[i] = val;
    }
	
public static void fill(boolean[] a, int fromIndex, int toIndex,
                            boolean val) {
        rangeCheck(a.length, fromIndex, toIndex);
        for (int i = fromIndex; i < toIndex; i++)
            a[i] = val;
    }
	
	public static void fill(double[] a, double val) {
	        for (int i = 0, len = a.length; i < len; i++)
	            a[i] = val;
	    }		

5. Conclusion


In this article, You've seen how to fill the whole array with one value using the utility method and Arrays.fill() method.

Arrays.fill() method supports to fill from a particular start index to end index.

Examples shown in this article are over GitHub.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How To Set All values of Array To Same Value In Faster Way?
How To Set All values of Array To Same Value In Faster Way?
A quick and fastest way to fill the array with the same value. Example program to create an array with n copies of the same value/object Arrays.fill()
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVCELoTAQcrevUu4Dm07DC3oMCAHBvaxHyfMPjhtUoLOKFPthnZh1eSq4tAqAerToUB4G3wHHsIrgTpFAgvpjjdxQX98PV2FLQydgyBcYWEl80Jge6RyndXH_g4b3Nc0tjSepAbfU725g/w640-h356/How+To+Set+All+values+of+Array+To+Same+Value+In+Faster+Way%253F.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVCELoTAQcrevUu4Dm07DC3oMCAHBvaxHyfMPjhtUoLOKFPthnZh1eSq4tAqAerToUB4G3wHHsIrgTpFAgvpjjdxQX98PV2FLQydgyBcYWEl80Jge6RyndXH_g4b3Nc0tjSepAbfU725g/s72-w640-c-h356/How+To+Set+All+values+of+Array+To+Same+Value+In+Faster+Way%253F.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/how-to-set-all-values-of-array-to-same-value-arrays-fill.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/how-to-set-all-values-of-array-to-same-value-arrays-fill.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content