从集合中获取元素 [英] Getting an element from a Set

查看:109
本文介绍了从集合中获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不设置一个操作来获取等于另一个元素的元素?

 设置< Foo> set = ...; 
...
Foo foo = new Foo(1,2,3);
Foo bar = set.get(foo); //从Set等于foo获取Foo元素

我可以询问Set是否包含元素等于bar,为什么我不能得到那个元素? :(



为了说明, equals 方法被覆盖,但它只检查其中一个字段, 。所以两个被认为相等的Foo对象实际上可能有不同的值,这就是为什么我不能使用 foo

如果相等,就没有必要获得元素。 Map 更适合这个用例。 / p>




如果您仍然想要查找元素,则没有其他选项,只能使用迭代器:

  public static void main(String [] args){

Set< Foo> set = new HashSet< Foo> ;
set.add(new Foo(Hello));

for(Iterator< Foo> it = set.iterator(); it.hasNext();){
Foo f = it.next();
if(f.equals(new Foo(Hello)))
System.out.println(foo found);
}
}

static class Foo {
String string;
Foo(String string){
this.string = string;
}
@Override
public int hashCode(){
return string.hashCode();
}
@Override
public boolean equals(Object obj){
return string.equals(((Foo)obj).string);
}
}


Why doesn't Set povide an operation to get an element that equals another element?

Set<Foo> set = ...;
...
Foo foo = new Foo(1, 2, 3);
Foo bar = set.get(foo);   // get the Foo element from the Set that equals foo

I can ask whether the Set contains an element equal to bar, so why can't I get that element? :(

To clarify, the equals method is overriden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use foo.

解决方案

There would be no point of getting the element if it is equal. A Map is better suited for this usecase.


If you still want to find the element you have no other option but to use the iterator:

public static void main(String[] args) {

    Set<Foo> set = new HashSet<Foo>();
    set.add(new Foo("Hello"));

    for (Iterator<Foo> it = set.iterator(); it.hasNext(); ) {
        Foo f = it.next();
        if (f.equals(new Foo("Hello")))
            System.out.println("foo found");
    }
}

static class Foo {
    String string;
    Foo(String string) {
        this.string = string;
    }
    @Override
    public int hashCode() { 
        return string.hashCode(); 
    }
    @Override
    public boolean equals(Object obj) {
        return string.equals(((Foo) obj).string);
    }
}

这篇关于从集合中获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆