Krzysztof Kazmierczyk
Krzysztof Kazmierczyk

Reputation: 539

How to fetch specific object from a set in Java

I would like quickly to fetch from Java Set the object equal to existing one. Is there any faster way than iterating for all elements of the set?

Here is my code:

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;
    }

}

and in the code:

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?
}

Is it possible to do it fast in Groovy?

Upvotes: 0

Views: 249

Answers (2)

rkj
rkj

Reputation: 9331

If you already have an object then there's no point in getting it from the Set. If you like to check if it exists in the set there is http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#contains(java.lang.Object)

Upvotes: 1

Amit Sharma
Amit Sharma

Reputation: 6184

There is not get method in java.util.Set interface. Hence, you can not fetch an entry :)

Maybe you are using the wrong data structure. May be what you need is a java.util.Map?

Upvotes: 6

Related Questions