Here you can find the source of intersection(int[] array1, int[] array2)
public static int[] intersection(int[] array1, int[] array2)
//package com.java2s; /*//from ww w. ja v a2 s . c o m * #%L * G * %% * Copyright (C) 2014 Giovanni Stilo * %% * G is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * <https://www.gnu.org/licenses/lgpl-3.0.txt>. * #L% */ import java.util.Arrays; public class Main { public static int[] intersection(int[] array1, int[] array2) { int[] intersection = new int[array1.length < array2.length ? array1.length : array2.length]; int k = 0; if (array1.length > 0 && array2.length > 0) { for (int i = 0, j = 0; i < array1.length && j < array2.length;) { if (array1[i] == array2[j]) { intersection[k] = array1[i]; k++; i++; j++; } if (j < array2.length && i < array1.length) { if (array2[j] < array1[i]) { j++; } else if (array2[j] > array1[i]) { i++; } } } } if (k < intersection.length) { intersection = Arrays.copyOf(intersection, k); } return intersection; } public static long[] intersection(long[] array1, long[] array2) { long[] intersection = new long[array1.length < array2.length ? array1.length : array2.length]; int k = 0; if (array1.length > 0 && array2.length > 0) { for (int i = 0, j = 0; i < array1.length && j < array2.length;) { if (array1[i] == array2[j]) { intersection[k] = array1[i]; k++; i++; j++; } if (j < array2.length && i < array1.length) { if (array2[j] < array1[i]) { j++; } else if (array2[j] > array1[i]) { i++; } } } } if (k < intersection.length) { intersection = Arrays.copyOf(intersection, k); } return intersection; } }