Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.fill complexity in java

How Arrays.fill(char[] a,char val) is implemented internally in java?

and what is the complexity of it?

like image 902
Ganesh Devadiga Avatar asked Apr 12 '26 00:04

Ganesh Devadiga


2 Answers

If you look into the definition of fill(char[] a, char val) available in java.util.Arrays Class.

it is such like this

public static void fill(Object[] a, Object val) {
        for (int i = 0, len = a.length; i < len; i++) //this loop will continues to the length of a.
            a[i] = val;
    }

So, Complexity for this method would be O(n). where n is the length of Object Array Object[] a which you passed to the parameter.

like image 65
Vikrant Kashyap Avatar answered Apr 14 '26 13:04

Vikrant Kashyap


The Java implementation uses a simple for loop. However, it is important to remember that the JVM often makes significant changes to internal functionality, and often replaces entire methods and classes with lower level implementations at runtime.

Often, depending on the target system, Arrays.fill can be replaced with something more like C/C++'s memset function, and as such, it will often run much faster than a regular for loop.

In all cases (as described by Vikrant's answer), the complexity should be considered O(N) where N is the total number of elements being set.

like image 39
KookieMonster Avatar answered Apr 14 '26 13:04

KookieMonster