Home > Net >  Can you override a function from a generically typed object?
Can you override a function from a generically typed object?

Time:12-28

I have a class in Java that stores generic Object types in a HashMap:

private final Map<Object, NetworkMarker> packetMarker = new WeakHashMap<>();

The packet Object is very large and the map has very high throughput, so the hashing of the packets alone takes up an absurd amount of cpu cycles, and I am curious if it's possible to minimize this, or I just need better hardware.

Would there be a way to override, despite being a generic Object class with no wrapper, the hashCode function to make it more efficient, or perhaps extend the hashmap to enhance the #get() method? Or any other method that I am overlooking!

Cheers!

EDIT for clarification: The packet Object is not typed. It is of the type Object. It's being passed in from an external source, so I cannot assign a type.

CodePudding user response:

You could always wrap it in another class that caches the hash code:

class CachedHash {
    public final Object cached;
    private Integer hashCode;

    public CachedHash(Object cached) {
        this.cached = cached;
    }

    @Override
    public boolean equals(Object o) {
        return cached.equals(o);
    }

    @Override
    public int hashCode() {
        if (hashCode == null) {
            hashCode = cached.hashCode();
        }
        return hashCode;
    }
}
  • Related