在我的情况下使用集中删除数组元素的重复 [英] Remove duplicated elements in array by using Set in my case
问题描述
我有一个 Array对象
,因为我使用的是第三方库,将阵列从库中调用一个方法了,我不能够访问 为MyObject
类
I have a Array
of object, since I am using a 3rd party library, the array is got by calling one method from the library, I am not able to access the MyObject
class.
//I have no access to MyObject class, I am sure the objects contain duplicated elements.
MyObject[] objects = SOME_LIB_CLASS.getObjects();
System.out.println("length is "+ objects.length); //length is 6
我尝试删除重复元素的对象,我用设置
:
Set<MyObject> objectSet = new HashSet<MyObject>(Arrays.asList(objects));
System.out.println("length is "+ objectSet.size()); //length is 6 still
但对象集
还包含重复的元素,为什么和放大器;如何通过数组迭代没有解决我的问题?
But the objectSet
still contains duplicated elements, why & how to solve my problem without iterate through the array?
推荐答案
如果设置仍含有重复的元素比你的对象的equals方法没有你希望它做什么。
If the set still contains "duplicate" elements than the equals method of your objects does not what you expect it to do.
在重复一个 HashSet的
是由确定等于
实施
如果您不能更改 MyObject.equals的实现()
(因为你没有源$ C $ C - 这是一个库类)我推荐使用 TreeSet的
键,提供特殊的比较。
If you can not change the implementation of MyObject.equals()
( because you don't have the source code - it is a library class), I recommend to use a TreeSet
and provide a special comparator.
例如
public class Main {
public static class MyObject {
public int value;
@Override
public String toString() {
return "MyObject [value=" + value + "]";
}
}
public static void main(String str[]) throws IOException {
Set<MyObject> myObjects = new TreeSet<MyObject>(
new Comparator<MyObject>() {
public int compare(MyObject object1, MyObject object2) {
return object1.value - object2.value;
}
});
addMyObjects(myObjects);
addMyObjects(myObjects); // try to add the duplicates
System.out.println(myObjects);
}
private static void addMyObjects(Set<MyObject> set){
for (int i = 0; i < 5; i++) {
MyObject myObject = new MyObject();
myObject.value = i;
set.add(myObject);
}
}
}
这篇关于在我的情况下使用集中删除数组元素的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!