CatalinGh CatalinGh - 2 months ago 16
Java Question

StackOverflowError when overriding Hashtable.contains() java

I have to make a class to inherit Hashcode and i need to override the contains method.

@Override
public boolean contains(Object value) {
if (!this.containsValue(value))
return true;
return false;
}

public void add(Object key, Object value) {
if (!this.contains(value)) {
this.put(key, value);
}
}


Compiles just fine but when i run it i get the StackOverflowError. I think i get some recursive infinite loop but i can't figure it out. Any help is welcomed!
printscreen of the error

Answer

You are calling containsValue inside contains but looking at the code in HashTable you can see that containsValue will call contains all over again and this will repeat until you get a stack overflow...

In HashTable.class

public boolean containsValue(Object value) {
    return contains(value);
}

You should really be doing this

@Override
public boolean contains(Object value) {
    if (!super.contains(value))
        return true;
    return false;
}

Or simply don't override contains because this is already doing what you're reimplementing.

Comments