Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write Java code to implement two different ways to find the intersection of two

ID: 3581983 • Letter: W

Question

Write Java code to implement two different ways to find the intersection of two lists of integers, given in the form arrays A and B. The intersection of A and B will give you the integer values common to both A and B but not anything else. The two arrays are of different sizes. In one implementation you will only use arrays and no other data structures and in the other in addition to the arrays you will use a HashSet.   In both methods, you will output the common values found in both A and B. You can test your code with some suitable values.

Explanation / Answer

import java.util.*;
import java.lang.*;
import java.io.*;


class Intersection
{
public static void IntersectionArray(int A[],int B[],int C[])
{
   int i,j,k=0;
   for(i=0;i <(A.length);i++)
{
for(j=0;j < B.length;j++)
{
if(A[i]==B[j]) //check if element is both in array A and B ,then put it in array C
{
C[k]=A[i];
  
k++;
}
  
else
continue;
  
}
}
  
  
System.out.println("Intersection of two array is " +" ");
for(i=0;i<k;i++)
{
System.out.print(" "+C[i]+" ");
}
  
}
public static void IntersectionHashSet()
{
  
   Set<Integer> A = new HashSet<Integer>();
   Set<Integer> B = new HashSet<Integer>();
  

   A.add(4); //add elements to Set A
   A.add(9);
   A.add(8);
   A.add(22);
   A.add(14);

  
   B.add(22); //add elements to set B
   B.add(7);
   B.add(8);

  
   Set<Integer> C = new HashSet<Integer>(A);
   C.retainAll(B); //retailall function will extract common elements
   System.out.println(" Intersection of two sets using HashSet: "+C.toString() );
  
  
}

   public static void main (String[] args)
   {
       int[] A= {4,9,8,22,14};
       int[] B= {22,7,8};
      
       int []C=new int[A.length+B.length];
  
IntersectionArray(A,B,C);
  
IntersectionHashSet();
  
   }
}

output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote