且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Java 中的辅助数组从列表中删除重复项?

更新时间:2023-09-26 19:29:46

你让事情变得很困难.让 Java 为您完成繁重的工作.例如 LinkedHashSet 为您提供唯一性并保留插入顺序.它也将比将每个值与每个其他值进行比较更有效.

You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.

double [] input = {1,2,3,3,4,4};
Set<Double> tmp = new LinkedHashSet<Double>();
for (Double each : input) {
    tmp.add(each);
}
double [] output = new double[tmp.size()];
int i = 0;
for (Double each : tmp) {
    output[i++] = each;
}
System.out.println(Arrays.toString(output));