Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果集合中有重复的值,如何从集合中删除该值_Java_Collections_Duplicates - Fatal编程技术网

Java 如果集合中有重复的值,如何从集合中删除该值

Java 如果集合中有重复的值,如何从集合中删除该值,java,collections,duplicates,Java,Collections,Duplicates,您好,我有一个集合,如果它有重复项,我想从集合中删除一个值。 如果我的值有重复项,我希望删除我的值和重复项 这是我收藏的声明: Collection<item> result = new Vector<item>(); 采集结果=新向量(); 我通过SQL查询完成了我的集合 如果你不想要重复,你应该考虑使用 SET/COD>。 SET/的作品是一个数学集合,所以它不允许重复它的性质。 实际上,每次您.add()并向其添加项时,它都会检查(通过.equals()和.h

您好,我有一个集合,如果它有重复项,我想从集合中删除一个值。 如果我的值有重复项,我希望删除我的值和重复项

这是我收藏的声明:

Collection<item> result = new Vector<item>();
采集结果=新向量();

我通过SQL查询完成了我的集合

如果你不想要重复,你应该考虑使用<代码> SET/COD>。

<代码> SET/<代码>的作品是一个数学集合,所以它不允许重复它的性质。

实际上,每次您
.add()
并向其添加项时,它都会检查(通过
.equals()
.hashCode()
)该项是否已在
集中。如果它这样做了,它就会忽略它

如果我的值有重复项,我希望删除我的值和重复项

以下是如何做到这一点:

1. Create a dictionary in which the key is an item, and the value is an int.
2. Enumerate the items in your collection. For each item:
   2.1. If the item is already in the dictionary, get the value, increment it,
        and put it back in the dictionary. Otherwise, put the item in the 
        dictionary with a value of 1.
3. Enumerate the items in your dictionary. For each item:
   3.1  Get the corresponding value of the item from the dictionary, and if 
        it is greater than 1, remove all occurrences of that item from the 
        collection.

当然,为了使其工作,您的“项”必须具有值语义,而不是对象语义。实际上,这意味着它必须有一个Equals()方法和一个GetHashCode()方法,该方法考虑的是对象的内容,而不是对象引用。

Simple。。使用
设置
。。它会处理复制品。它会处理复制品,但它会处理我的价值和他的复制品?你考虑过回答别人的问题吗?82个问题,0个答案…如果你的收藏类型复杂(比如“人”),对吗?如果是这样,你可以考虑在它的类中编写<代码> .RealSald()/Cuth>方法。你可以将列表中的所有元素添加到一个集合中。顺便说一句,我不会使用Vector,它不太可能是列表的最佳选择。@EvertonAgner和
hashCode()
方法。@Mercer:只需这样做:
Set=newhashset(result)。现在在集合中不会有重复的。所有重复项都将根据
item
类的
.equals
.hashCode
方法删除。OP说他需要删除所有重复项;这意味着项目及其副本。不能为此使用集合。此外,如果问题只是删除重复项,那么他可以在SQL查询中使用DISTINCT,我们就不会有这个问题。