Java Array Unique unique(Object[] elements)

Here you can find the source of unique(Object[] elements)

Description

Return a set (array of unique objects).

License

Open Source License

Parameter

Parameter Description
elements array of objects, possibly with duplicates

Return

array of objects with duplicates removed; order is not preserved.

Declaration

public static Object[] unique(Object[] elements) 

Method Source Code

//package com.java2s;
// Refer to LICENSE for terms and conditions of use.

import java.util.*;

public class Main {
    /**//w ww. j  a v  a  2 s  .  com
     * Return a set (array of unique objects).
     *
     * @param elements array of objects, possibly with duplicates
     * @return array of objects with duplicates removed; order is not preserved.
     */
    public static Object[] unique(Object[] elements) {
        Hashtable h = new Hashtable();
        Object o = new Object();
        for (int i = 0; i < elements.length; i++) {
            h.put(elements[i], o);
        }
        Object[] el2 = new Object[h.size()];
        Enumeration e = h.keys();
        int i = 0;
        while (e.hasMoreElements()) {
            el2[i++] = e.nextElement();
        }
        return el2;
    }

    /**
     * Same as unique, but for Strings.
     *
     * @param elements array of Strings, possibly with duplicates
     * @return array of Strings with duplicates removed; order is not preserved.
     */
    public static String[] unique(String[] elements) {
        Hashtable h = new Hashtable();
        Object o = new Object();
        for (int i = 0; i < elements.length; i++) {
            h.put(elements[i], o);
        }
        String[] el2 = new String[h.size()];
        Enumeration e = h.keys();
        int i = 0;
        while (e.hasMoreElements()) {
            el2[i++] = (String) e.nextElement();
        }
        return el2;
    }
}

Related

  1. getUniqueWords(String[] input)
  2. invertRelabeling(int[] relabeling, int[] uniqueVars, int maxVarNum)
  3. unique(double[] in)
  4. unique(int[] a, int aLen, int[] b, int bLen)
  5. unique(int[] array)
  6. uniqueInts(int[] ints)
  7. uniques(final int[] ints)