Skip to content
Advertisement

Java Generics – quick question on Greater Than Method with Objects

I have an assignment in my Java class, we are learning Generics, I have looked in my notes, my lessons, and even on the internet and I still cant figure out what this last assignment question is asking me to do, which is:

Write a generic “greater-than” function that takes two objects as arguments, each of which has a “value” method which returns an integer and returns the argument whose “value” method returns the larger integer. Your generic function should constrain its type argument so that types without a “value” method cannot be used.

Is there a reason why “value” in quotation marks and how can a method constrain its type argument so that types without a “value” method cant be used. I’m mainly asking for clarification or maybe a little example. Am I creating a Value class and then doing something like this:

JavaScript

Advertisement

Answer

They are apparently asking you to implement a generic maxByValue method. Since greater-than contains a hyphen, and is thus an invalid Java identifier anyway, I’ll stick to maxByValue.

The requirement of having a value method is mentioned a few times, so let’s encode it as an interface:

JavaScript

Now, the main point of having a generic parameter here is to make sure that the return type of the maxByValue is specific enough to be useful. Let’s call this type T. In order for the arguments to be comparable, T must be a subtype of Value. The only meaningful source for obtaining the return type is from the types of arguments. Putting together the three points:

  • Type parameter T subtype Value
  • Type inferred from the arguments
  • Result type is T

gives you the signature:

JavaScript

There are basically just two meaningful ways of implementing this. Let’s take the left-biased one (i.e. left argument is returned if value is the same):

JavaScript

Let’s try it on a trivial integer example:

JavaScript

So far so good. Let’s see how precise the type inference is:

JavaScript

The point to see here is the following. We have the following subtyping relation:

JavaScript

and the following least upper bounds for the concrete instances:

JavaScript

(and all symmetric cases too).

Now, when we

  • put two cars into maxByValue, we get out a car (first example), but
  • when we put a car and a train into maxByValue, we get a more general Vehicle, so that the car-specific methods become unavailable (examples two and three; third does not compile – rightly so, because a train has no car-methods).
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement