Java Array Intersect intersect(T[] a, T[] b)

Here you can find the source of intersect(T[] a, T[] b)

Description

Finds the intersection of two sorted arrays.

License

Open Source License

Parameter

Parameter Description
a a sorted array
b a sorted array of similar size to <code>a</code>
T element type

Return

the intersection of two sorted arrays

Declaration

public static <T extends Comparable<T>> Object[] intersect(T[] a, T[] b) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/*from  www.j a v  a2  s.c o m*/
     * Finds the intersection of two sorted arrays.
     *
     * @param a   a sorted array
     * @param b   a sorted array of similar size to <code>a</code>
     * @param <T> element type
     * @return the intersection of two sorted arrays
     */
    public static <T extends Comparable<T>> Object[] intersect(T[] a, T[] b) {
        if (a.length == 0 || b.length == 0)
            return new Object[0];
        List<T> ret = new ArrayList<>();
        int i = 0;
        for (T val : a) {
            while (i < b.length && val.compareTo(b[i]) > 0) {
                ++i;
            }
            if (i < b.length && val.compareTo(b[i]) == 0) {
                ret.add(val);
                ++i;
            }
        }
        return ret.toArray();
    }
}

Related

  1. intersect(boolean[] mask, int[] examples, boolean[] intersection)
  2. intersect(int[] sorted1, int[] sorted2)
  3. intersect(int[]... arrays)
  4. intersect(String[] arr1, String[] arr2)
  5. intersect(String[] list1, String[] list2)
  6. intersect(T[] a, T[] b)
  7. intersectArrays(int[] a, int[] b)
  8. intersectArrays(int[] targetArray, int[] selfArray)
  9. intersection(final long[] array1, final long[] array2)