Java Set 集合中的重复值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2112539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:39:37  来源:igfitidea点击:

Duplicate values in the Set collection?

javacollections

提问by Johanna

Is it possible to allow duplicate values in the Set collection?

是否可以在 Set 集合中允许重复值?

Is there any way to make the elements unique and have some copies of them? Is there any functions for Set collection for having duplicate values in it?

有什么方法可以使元素独一无二并拥有它们的一些副本?Set 集合中是否有任何函数用于在其中包含重复值?

采纳答案by Schildmeijer

Ever considered using a java.util.Listinstead?

有没有考虑过使用java.util.List代替?

Otherwise I would recommend a Multisetfrom Google Guava(the successor to Google Collections, which this answer originally recommended -ed.).

否则,我会建议多集,从谷歌番石榴(继任者谷歌集合,此答案原本建议-ed)。

回答by Dan Polites

I don't believe that you can have duplicate values within a set. A set is defined as a collection of unique values. You may be better off using an ArrayList.

我不相信你可以在一个集合中有重复的值。集合被定义为唯一值的集合。使用 ArrayList 可能会更好。

回答by Kartoch

I don't think so. The only way would be to use a List. You can also trick with function equals(), hashcode() or compareTo() but it is going to be ankward.

我不这么认为。唯一的方法是使用列表。您也可以使用函数 equals()、hashcode() 或 compareTo() 来欺骗,但这会很尴尬。

回答by George Armhold

The very definitionof a Set disallows duplicates. I think perhaps you want to use another data structure, like a List, which will allow dups.

非常定义一组不允许重复。我想也许你想使用另一种数据结构,比如List,它允许重复。

Is there any way to make the elements unique and have some copies of them?

有什么方法可以使元素独一无二并拥有它们的一些副本?

If for some reason you really doneed to store duplicates in a set, you'll either need to wrap them in some kind of holder object, or else override equals() and hashCode() of your model objects so that they do not evaluate as equivalent (and even thatwill fail if you are trying to store references to the same physical object multiple times).

如果由于某种原因,你真的需要存储重复一组,你要么需要将它们包装在某种持有人的对象,否则覆盖equals()和模型的hashCode()方法对象,使他们不评价作为等价的(如果您尝试多次存储对同一物理对象的引用,即使这样也会失败)。

I think you need to re-evaluate what you are trying to accomplish here, or at least explain it more clearly to us.

我认为您需要重新评估您在这里尝试完成的工作,或者至少向我们更清楚地解释它。

回答by giri

NO chance.... you can not have duplicate values in SET interface... If you want duplicates then you can try Array-List

没有机会......你不能在 SET 接口中有重复的值......如果你想要重复,那么你可以尝试 Array-List

回答by Cuga

From the javadocs:

从javadocs:

"sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one nullelement"

“集合不包含一对元素 e1 和 e2,使得 e1.equals(e2),最多一个null元素”

So if your objects were to override .equals() so that it would return different values for whatever objects you intend on storing, then you could store them separately in a Set(you should also override hashcode() as well).

因此,如果您的对象要覆盖 .equals() 以便它为您打算存储的任何对象返回不同的值,那么您可以将它们单独存储在 a 中Set(您还应该覆盖 hashcode() )。

However, the very definition of a Setin Java is,

然而,SetJava中 a 的定义是,

"A collection that contains no duplicate elements. "

“一个不包含重复元素的集合。”

So you're really better off using a Listor something else here. Perhaps a Map, if you'd like to store duplicate values based on different keys.

所以你最好List在这里使用 a或其他东西。也许 a Map,如果您想根据不同的键存储重复的值。

回答by Gladwin Burboz

Sun's view on "bags" (AKA multisets):

Sun 对“包”(又名多重集)的看法:

We are extremely sympathetic to the desire for type-safe collections. Rather than adding a "band-aid" to the framework that enforces type-safety in an ad hoc fashion, the framework has been designed to mesh with all of the parameterized-types proposals currently being discussed. In the event that parameterized types are added to the language, the entire collections framework will support compile-time type-safe usage, with no need for explicit casts. Unfortunately, this won't happen in the the 1.2 release. In the meantime, people who desire runtime type safety can implement their own gating functions in "wrapper" collections surrounding JDK collections.

我们非常认同类型安全集合的需求。该框架并没有向框架中添加一个“创可贴”,以特别的方式强制执行类型安全,而是设计为与当前正在讨论的所有参数化类型建议相结合。如果将参数化类型添加到语言中,整个集合框架将支持编译时类型安全使用,无需显式强制转换。不幸的是,这不会发生在 1.2 版本中。同时,希望运行时类型安全的人可以在围绕 JDK 集合的“包装器”集合中实现他们自己的门控函数。

(source; note it is old and possibly obsolete -ed.)

来源;请注意它已经过时并且可能已经过时。)

Apart from Google's collections API, you can use Apache Commons Collections.

除了 Google 的集合 API,您还可以使用 Apache Commons 集合。

Apache Commons Collections:

Apache Commons 集合:

http://commons.apache.org/collections/

http://commons.apache.org/collections/

Javadoc for Bag

Javadoc 用于 Bag

回答by VHF

As mentioned choose the right collection for the task and likely a List will be what you need. Messing with the equals(), hashcode() or compareTo() to break identity is generally a bad idea simply to wedge an instance into the wrong collection to start with. Worse yet it may break code in other areas of the application that depend on these methods producing valid comparison results and be very difficult to debug or track down such errors.

如前所述,为任务选择正确的集合,可能需要一个列表。使用 equals()、hashcode() 或 compareTo() 来破坏身份通常是一个坏主意,只是简单地将实例插入错误的集合中。更糟糕的是,它可能会破坏应用程序其他领域的代码,这些领域依赖于这些方法产生有效的比较结果,并且很难调试或追踪此类错误。

回答by IndicCrusader

This question was asked to me also in an interview. I think the answer is, ofcourse Set will not allow duplicate elements and instead ArrayList or other collections should be used for the same, however overriding equals() for the type of the object being stored in the set will allow you to manipulate on the comparison logic. And hence you may be able to store duplicate elements in the Set. Its more of a hack, which would allow non-unique elements in the Set and ofcourse is not recommended in production level code.

这个问题也是在一次采访中问到我的。我认为答案是,当然 Set 不允许重复元素,而 ArrayList 或其他集合应该用于相同的元素,但是覆盖存储在集合中的对象类型的 equals() 将允许您操作比较逻辑。因此,您可以在 Set 中存储重复的元素。它更像是一种 hack,这将允许 Set 中的非唯一元素,当然不建议在生产级代码中使用。

回答by The PowerHouse

You can do so by overriding hashcode as given below:

您可以通过覆盖如下所示的哈希码来实现:

public class Test  
{  
    static int a=0;  

    @Override  
    public int hashCode()  
    {  
        a++;  
        return a;  
    }

    public static void main(String[] args)
    {
        Set<Test> s=new HashSet<Test>();
        Test t1=new Test();
        Test t2=t1;
        s.add(t1);
        s.add(t2);
        System.out.println(s);
        System.out.println("--Done--");
    }
}