1. Introduction

Finding the intersection of two arrays involves determining which elements are common to both arrays. In Java, this can be accomplished using collections like Set. In this tutorial, we will discuss a method to find the intersection of two arrays.

2. Program Steps

1. Initialize two arrays with elements.

2. Convert the arrays to Set objects to facilitate the intersection operation.

3. Use the retainAll method on one of the sets, passing the other set as a parameter, to perform the intersection.

4. Convert the resultant set back to an array.

5. Display the intersection array.

3. Code Program

import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;

public class ArrayIntersection {

    public static void main(String[] args) {
        // Step 1: Initialize two arrays with elements
        Integer[] array1 = {1, 2, 3, 4, 5};
        Integer[] array2 = {4, 5, 6, 7, 8};

        // Step 2: Convert the arrays to Set objects
        Set<Integer> set1 = new HashSet<>(Arrays.asList(array1));
        Set<Integer> set2 = new HashSet<>(Arrays.asList(array2));

        // Step 3: Use retainAll method to find intersection of set1 and set2
        set1.retainAll(set2);

        // Step 4: Convert the resultant set back to an array
        Integer[] intersectionArray = set1.toArray(new Integer[0]);

        // Step 5: Display the intersection array
        System.out.println("Intersection of the two arrays: " + Arrays.toString(intersectionArray));
    }
}

Output:

Intersection of the two arrays: [4, 5]

4. Step By Step Explanation

In Step 1, we initialize two Integer arrays array1 and array2 with some elements.

In Step 2, we convert array1 and array2 to Set objects set1 and set2 respectively, using Arrays.asList(array).

Step 3 involves performing the intersection operation. The retainAll method is used on set1, passing set2 as the parameter. This method retains only the elements in this set that are contained in the specified collection (set2 in this case). So, after this operation, set1 will only contain the elements common to both set1 and set2.

In Step 4, we convert the resultant set1 back to an array named intersectionArray using the toArray method.

Finally, in Step 5, we print out the intersectionArray using the Arrays.toString() method, which contains the common elements of array1 and array2.