Alexandru N. Onea
Alexandru N. Onea

Reputation: 423

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

Upvotes: 1

Views: 4533

Answers (2)

dreamcrash
dreamcrash

Reputation: 51413

The problem is that you do not have the same object, but rather two different objects with the same Key.

This:

Entry sample = new Entry(key, new CustomSet());

makes a new object, and if you now call entries.add(sample) and then try to call entries.contains(sample) it will return true, since it is the same object, indeed. However, that would not be the case if you would have something like:

 Entry sample = new Entry(key, new CustomSet());
 Entry sample1 = new Entry(key, new CustomSet());

 entries.add(sample);

 if(entries.contains(sample1)) // It will still return false.

The solution involves the redefinition of the method equals using the keys to differenciate objects. So in the Entry class you should add the following:

 public boolean equals(Object o)
 {
       if(o == null || !getClass().equals(o.getClass()))  return false;
       if(o == this)  return true;
         
       Entry p = (Entry) o;
       return this.key.compareTo(p.key) == 0;
}

Upvotes: 2

Fritz
Fritz

Reputation: 10045

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.

Upvotes: 6

Related Questions