Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing generic types Java

I have a problem with comparing generic types. In C# I've always done something like: class Element<T, V> where T : IComparable<T>.

My question is how can it be written in java?

like image 925
zyks Avatar asked Apr 02 '13 18:04

zyks


People also ask

What is generic comparable?

Comparability expresses the innate ability to be sorted in a list, and so many Java types are comparable, like Integer, String, etc. The way a class implements this interface is that T must be the class itself, for example, if you look at the String class: public class String implements Comparable<String> ...

How can you bound generic types?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.

Can generic types be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!


1 Answers

I suspect you want something like:

class Element<T extends Comparable<T>>

... using the Comparable interface and a bounded type parameter.

like image 51
Jon Skeet Avatar answered Oct 06 '22 08:10

Jon Skeet