一般如何从数组中删除重复项?

How to remove duplicates from an array generically?

这是我现在的代码

public class removerDuplicados<T> {

    public removerDuplicados() {
    }

    public T[] removerDups(T [] arr) {
        T[] res = Arrays.stream(arr).distinct().toArray();
        return res;
    }
}

但是这一行

T[] res = Arrays.stream(arr).distinct().toArray();

给我不兼容的类型错误

这会奏效。只需调用 removerDuplicados.removerDups( ARRAY_NAME )

import java.util.Arrays;

public class removerDuplicados<T>
{
    @SuppressWarnings("unchecked")
    public static <T> T[] removerDups(T [] arr)
    {
        return ( (T[]) (Arrays.stream(arr).distinct().toArray()) ) ;
    }
}

有趣的是,你不能对集合做这个特殊的技巧,其中类型被擦除,但你可以用数组:

// this method can be static
@SuppressWarnings("unsafe") // safe because we're getting the type from the array object
public static <T> T[] removeDups(T[] arr) {
  // 
  Class<T> componentType = (Class<T>) arr.getClass().getComponentType();

  return Arrays.stream(arr)
    .distinct()
    .toArray(size -> (T[]) Array.newInstance(componentType, size));
}

试试这个。 该副本是多余的,但可以在没有反射、转换或警告的情况下进行编译。

public static <T> T[] removerDups(T [] arr) {
    return Arrays.stream(arr)
        .distinct()
        .toArray(n -> Arrays.copyOf(arr, n));
}

public static void main(String[] args) {
    String[] array = {"a", "b", "a"};
    String[] uniq = removerDups(array);
    System.out.println(Arrays.toString(uniq));
}

输出:

[a, b]