Interfaces for Custom Array Manipulation in Java


Create a Java program to demonstrate the use of an interface for custom array manipulation

  • An array of integers numbers is defined.
  • An instance of ArrayProcessor named doubler is created using a lambda expression. This instance doubles each element of the array passed to it.
  • The processArray method of the ArrayProcessor instance doubler is called with the numbers array as the argument.
  • Finally, the doubled array is printed using Arrays.toString() method.

Source Code

import java.util.Arrays;
interface ArrayProcessor 
{
	void processArray(int[] array);
}
 
public class Main
{
	public static void main(String[] args)
	{
		int[] numbers = {1, 2, 3, 4, 5};
		ArrayProcessor doubler = array -> {
			for (int i = 0; i < array.length; i++)
			{
				array[i] *= 2;
			}
		};
 
		doubler.processArray(numbers);
		System.out.println("Doubled Array : " + Arrays.toString(numbers));
	}
}

Output

Doubled Array : [2, 4, 6, 8, 10]

Example Programs