Skip to content
Advertisement

How to check if user defined entry in vector in java?

I have a vector of entries. Each entry is an instance of this class:

public class Entry implements Comparable<Entry>{

    private String _key;
    private CustomSet _value;

    [...]

    @Override
    public int compareTo(Entry a) {
        return this._key.compareTo(a._key);
    }
}

The vector is declared as shown below:

Vector<Entry> entries = new Vector<Entry>();

After that, the vector is populated. Then I want to check if certain key is somewhere in the vector. So I do this:

Entry sample = new Entry(key, new CustomSet());
if (entries.contains(sample)) {
    // do something
}

This seems not to work. Why? How can I get it to work?

P.S. CustomSet is another user defined class, irrelevant from my point of view

Advertisement

Answer

You have to redefine the equals method in your Entry class, because that’s what contains relies in to determine if an element belongs to a collection, as the docs say:

Returns true if this vector contains the specified element. More formally, returns true if and only if this vector contains at least one element e such that (o==null ? e==null : o.equals(e)).

In this case o is contain‘s method parameter.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement