首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么java.util.HashSet没有get(Object o)方法?

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

Stack Overflow用户
提问于 2012-12-13 23:53:36
回答 8查看 92.6K关注 0票数 63

我见过其他关于基于索引值从Set获取对象的问题,我理解为什么这是不可能的,但我没有找到一个很好的解释为什么get by object是不允许的,所以我想我会问。

HashSet是由HashMap支持的,所以从它获取一个对象应该是相当简单的。现在看来,我必须遍历HashSet中的每一项并测试相等性,这似乎是不必要的。

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

例如,假设我有Foo.java

代码语言:javascript
复制
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

代码语言:javascript
复制
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)就足够了)?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13863506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档