dinesh babu
dinesh babu

Reputation: 59

How to remove an object from priority queue of user defined type

i have my priority queue defined as

PriorityQueue< LRUCache > qu = new PriorityQueue<>(new Comp() );

here LRUCache class has the variable key and freq based on which i created the Comparator. if i have to remove a particular object from priority queue based on certain key and freq how can i do that

qu.remove(new LRUCache(key , freq ) ) // like this or something better ??

Upvotes: 0

Views: 815

Answers (1)

0xh3xa
0xh3xa

Reputation: 4859

Yes, you can but first, the equals() method in your LRUCache class because the PriorityQueue uses it internally for finding the object to remove it.

i.e this is the indexOf(...) code from the PriorityQueue which called be remove(...) method

    private int indexOf(Object o) {
        if (o != null) {
            final Object[] es = queue;
            for (int i = 0, n = size; i < n; i++)
                if (o.equals(es[i]))
                    return i;
        }
        return -1;
    }

, Just add to your LRUCache class the equals()

The equals(...) method will check the following:

1- Check if the obj parameter equals the current object with this keyword then return true

2- Check if the obj parameter equals null or not the same class "invalid state" then return false

3- Otherwise the obj parameter will be valid and the same type, so cast to the target class which is here LRUCache, and check with whatever properties in the class based on your needs, here they are key and freq

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null || obj.getClass() != this.getClass())
                return false;
            LRUCache cache = (LRUCache) obj;
            return key.equals(cache.key) && freq == cache.freq;
        }

Upvotes: 1

Related Questions