java - 为什么 java.util.HashSet 没有 get(Object o) 方法?

标签 java hashset

我已经看到其他关于根据索引值从 Set 获取对象的问题,我理解为什么这是不可能的。但是我无法找到一个很好的解释来解释为什么不允许通过对象获取,所以我想我会问。

HashSetHashMap 支持,因此从中获取对象应该非常简单。就像现在一样,看来我必须遍历 HashSet 中的每个项目并测试似乎没有必要的相等性。

我可以只使用 Map 但我不需要 key:value 对,我只需要一个 Set

例如说我有 Foo.java:

package example;

import java.io.Serializable;

public class Foo implements Serializable {

    String _id;
    String _description;

    public Foo(String id){
        this._id = id
    }

    public void setDescription(String description){
        this._description = description;
    }

    public String getDescription(){
        return this._description;
    }

    public boolean equals(Object obj) {
        //equals code, checks if id's are equal
    }

    public int hashCode() {
        //hash code calculation
    }

}

Example.java:

package example;

import java.util.HashSet;

public class Example {

    public static void main(String[] args){
        HashSet<Foo> set = new HashSet<Foo>();

        Foo foo1 = new Foo("1");
        foo1.setDescription("Number 1");

        set.add(foo1);
        set.add(new Foo("2"));

        //I want to get the object stored in the Set, so I construct a object that is 'equal' to the one I want.
        Foo theFoo = set.get(new Foo("1")); //Is there a reason this is not allowed?
        System.out.println(theFoo.getDescription); //Should print Number 1
    }

}

是否因为 equals 方法旨在测试“绝对”相等而不是“逻辑”相等(在这种情况下 contains(Object o) 就足够了)?

最佳答案

Java map /集合备忘单

它会包含键/值对还是仅包含值?

1) If it contains pairs, the choice is a map. Is order important?

. 1-1) If yes, follow insertion order or sort by keys?

。 . 1-1-1) 如果已订购,LinkedHashMap

。 . 1-1-2) 如果已排序,TreeMap

。 1-2) 如果顺序很重要,HashMap

2) If it stores only values, the choice is a collection. Will it contain duplicates?

。 2-1) 如果ArrayList

. 2-2) If it will not contain duplicates, is primary task searching for elements (contains/remove)?

。 . 2-2-1) 如果 noArrayList

. . 2-2-2) If yes, is order important?

。 . . 2-2-2-1) 如果顺序重要,HashSet

. . . 2-2-2-2) If yes, follow insertion order or sort by values?

。 . . . 2-2-2-2-1) 如果有序LinkedHashSet

。 . . . 2-2-2-2-2) 如果排序TreeSet

关于java - 为什么 java.util.HashSet 没有 get(Object o) 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13863506/

相关文章:

java - 集合和 StringBuilder 的奇怪行为

java - 递增原始类型的 MAX_VALUE

java - 当 TextField 中的字符串超过 5 个字符时启用按钮

c# - 从字符串列表中获取不同且有序的成员 - linq 或 hashset for unique 哪个更快/更适合

来自 Maven 的 Java OpenCV

java - JGit 中的子树推送

java - 当找到多个集合的交集时,使用retainAll()的最快顺序

java - 无论顺序如何,Hashset 上的 .equals 是否返回 true?

java - 自定义 equals() 方法无法正常工作

C# list - 通过比较特定属性消除重复项