Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics and Infinity (Comparable)

With the type Integer you can do this:

int lowest = Integer.MIN_VALUE;

What can I do if I use generics?

K lowest = <...>;

I need this in order to implement something similar to a PriorityQueue. I have access to a node I want to remove from the queue, but it is not the min.

1. I need to make it the min by decreasing the key of that node,
2. And then remove the min.

I am stuck on the first step. The only thing I can do is set the key of the node to the current min. Not sure it is enough.

like image 978
Flavio Martins Avatar asked Apr 29 '09 18:04

Flavio Martins


People also ask

What are two benefits of using generics?

Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced. Better performance.

Can I use polymorphism in generics?

The polymorphism applies only to the 'base' type (type of the collection class) and NOT to the generics type.


2 Answers

There is no generic form of MIN_VALUE or MAX_VALUE for all Comparable types.

Think about a Time class that implements comparable. There is no MAX_VALUE for Time even though it is Comparable.

like image 56
Alex B Avatar answered Oct 26 '22 17:10

Alex B


I am trying to imagine what scenario would require such behavior. This is the best I can come up with...

WARNING: This code is dangerous. Please be merciful to me for posting such an abomination. It is only a proof of concept.

public class Lowest<K> implements Comparable<K> {
    public int compareTo(K other) {
        return -1;
    }
}

And then...

public class Test {
    public <K extends Comparable<K>> K findMaximum(List<K> values) throws Exception {
        K lowest = (K) new Lowest<K>(); /// XXX DANGER! Losing compile-time safety!!!

        K maximum = lowest;
        for (K value : values) {
            if (maximum.compareTo(value) < 0) {
                maximum = value;
            }
        }

        if (maximum == lowest) {
            throw new Exception("Could not find a maximum value");
        } else {
            return maximum;
        }
    }
}
like image 27
Adam Paynter Avatar answered Oct 26 '22 17:10

Adam Paynter