Question

I am trying to learn generics in java. I see that at class level we can specify bounded type parameters as class Stats <T extends Number>.

Let's say that the class has an array of type T and an average method to calculate the average of those T's and another method to check if the averages of two objects are the same or not.

However, at the method level inside the class I can't do this:
boolean isAverageSame(Stats<T extends Number> ob) if I want to find that averages of two objects are the same or not.

Instead I have to do:
boolean isAverageSame(Stats<?> ob)

Why is this the case? Is this just how the syntax was defined in java or I am missing something?

Thanks.

Was it helpful?

Solution

It sounds like you want to declare a new generic parameter for the method, in which case you could use:

<U extends Number> boolean isAverageSame(Stats<U> ob)

Note that this will allow you to do something like:

Stats<Integer> x = ...;
Stats<Float> y = ...;
boolean z = x.isAverageSame(y);

Is that what you want? If you only want to be able to compare a Stats<Integer> with a Stats<Integer> (etc) then you just need:

boolean isAverageSame(Stats<T> ob)

... in other words, the method won't introduce another generic type parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top