Here you can find the source of intersect(T[] a, T[] b)
Parameter | Description |
---|---|
a | the first array |
b | the second array |
public static <T> T[] intersect(T[] a, T[] b)
//package com.java2s; import java.util.*; public class Main { /**/*from ww w .ja v a2s .co m*/ * Create an intersection of two arrays, removing null values and duplicates * * @param a the first array * @param b the second array * @return the intersection */ public static <T> T[] intersect(T[] a, T[] b) { ArrayList<T> l = new ArrayList<T>(); for (int i = 0; i < a.length; i++) { if (a[i] == null) continue; for (int j = 0; j < b.length; j++) { if (b[j] == null) continue; if (a[i].equals(b[j])) { if (!l.contains(a[i])) l.add(a[i]); break; } } } T[] t = Arrays.<T>copyOf(a, l.size()); for (int i = 0; i < t.length; i++) t[i] = l.get(i); return t; } /** * Determine whether the array contains the given element * * @param a the array * @param e the element * @return true if the element is in the array */ public static <T> boolean contains(T[] a, T e) { if (a == null) return false; for (int i = 0; i < a.length; i++) { if (a[i] == e) return true; if (e != null && e.equals(a[i])) return true; } return false; } }