Java – Array operations

  • Arrays.fill() can be used to fill an array with the same value
 

package com.pwn.array;

import java.util.Arrays;

/*Filling an array after initialization*/
public class ArrayFill {

	public static void main(String[] args) {
		String[] strArray = new String[3];
		Arrays.fill(strArray, "abc");
		System.out.println(Arrays.toString(strArray));

	}

}

[abc, abc, abc]

  • Arrays.setAll can be used to set every element of an array to generated values.
 
package com.pwn.array;

import java.util.Arrays;

/* setAll can be used to set every element of an array to generated values. 
 * These methods are passed a generator function which accepts an index 
 * and returns the desired value for that position.*/

public class ArryFillUsingIndx {

	public static void main(String[] args) {
		int[] intArray = new int[5];
		Arrays.setAll(intArray, i -> i + 1);
		System.out.println(Arrays.toString(intArray));

	}

}
 
[1, 2, 3, 4, 5] 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s