如何在Java中从集合中获取特定对象

如何在Java中从集合中获取特定对象,java,groovy,set,Java,Groovy,Set,我想快速地从Java获取与现有对象相等的对象。有没有比迭代集合中所有元素更快的方法 这是我的密码: class A { int a,b,c,d; public A(int a, int b, int c, int d) { this.a = a; this.b = b; this.c = c; this.d = d; } @Override public int hashCode() {

我想快速地从Java获取与现有对象相等的对象。有没有比迭代集合中所有元素更快的方法

这是我的密码:

class A {
    int a,b,c,d;

    public A(int a, int b, int c, int d) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + getOuterType().hashCode();
        result = prime * result + a;
        result = prime * result + b;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        A other = (A) obj;
        if (!getOuterType().equals(other.getOuterType()))
            return false;
        if (a != other.a)
            return false;
        if (b != other.b)
            return false;
        return true;
    }

    private Main getOuterType() {
        return Main.this;
    }

}
在守则中:

void run() {
    Set<A> a = new HashSet<>();
    a.add(new A(1,2,3,4));
    a.add(new A(2,3,4,5));

    A b = new A(1,2,3,5);
    //How to fetch from set a object equal to object b?
}
在Groovy中可以快速完成吗?

java.util.Set接口中没有get方法。因此,您无法获取条目:


可能您使用了错误的数据结构。可能您需要的是java.util.Map?

如果您已经有了一个对象,那么从集合中获取它就没有意义了。如果要检查集合中是否存在,则有http://docs.oracle.com/javase/7/docs/api/java/util/Set.htmlcontainsjava.lang.Object

您不能从集合中检索任何内容。如果你的集合包含你的对象,那么你已经拥有了它。@SotiriosDelimanolis好吧,你只有一个相等的对象,而不是相同的对象。@edgar除非你做的是引用相等的事情,只要它们相等,那又有什么关系呢?他可能有一个来自数据库或其他东西的集合,想要像Person p=new PersonSmith,John;Person john=set.getp;其中包含个人的所有实际记录。如果需要访问集合元素,您可以对集合元素进行迭代。嗯,他需要某种java.util.Map,无论是HashMap、TreeMap还是其他子类型。