Finding the difference of two arrays.
Here’s a Java program that finds the difference between two arrays:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayDifference { public static void main(String[] args) { int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = {4, 5, 6, 7, 8}; int[] difference = findDifference(array1, array2); System.out.println("Array Difference: " + Arrays.toString(difference)); } public static int[] findDifference(int[] array1, int[] array2) { List<Integer> differenceList = new ArrayList<>(); for (int num : array1) { if (!contains(array2, num)) { differenceList.add(num); } } int[] differenceArray = new int[differenceList.size()]; for (int i = 0; i < differenceList.size(); i++) { differenceArray[i] = differenceList.get(i); } return differenceArray; } public static boolean contains(int[] array, int num) { for (int i : array) { if (i == num) { return true; } } return false; } }
In this program, we have the `findDifference` method that takes two arrays as input and returns an array containing the elements that are present in the first array but not in the second array. The `contains` method is a helper method that checks whether a given number is present in the array.
In the `main` method, we have two example arrays `array1` and `array2`. We call the `findDifference` method with these arrays and store the result in the `difference` array. Finally, we print the `difference` array to display the elements that are different between the two arrays.
Running this program will give you the output:
Array Difference: [1, 2, 3]
Here, the elements 1, 2, and 3 are present in `array1` but not in `array2`, so they are considered as the difference.