Ganesh Devadiga
Ganesh Devadiga

Reputation: 57

Arrays.fill complexity in java

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

and what is the complexity of it?

Upvotes: 3

Views: 8187

Answers (2)

KookieMonster
KookieMonster

Reputation: 503

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.

Upvotes: 7

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

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.

Upvotes: 9

Related Questions