Definition of generics

I cannot understand the whole generic declaration, even after reading countless articles and entries in Java books, none of them seem to explain this in a simple and clean way. Please can someone explain this to me ?:

class Something<T> {...}

I know what T is, and I understand that we use generics when we want to write a general definition / method for any type of Object type that we pass, instead we have different types of methods specific to one type of Object extension, we write one general, which may include one or more types (hence, uppercase T). But one thing that annoys me the most is the following ad example:

public <T extends Comparable<T>> void Something{...}

Primarily; A comparable interface is not a class (correct me if I am wrong), so why is it extendsinstead implements. Now, why does it need to be announced (this whole thing <T ...>) before voidand now Comparable<T>? What does it mean? What type of object that receives should have implements Comparable<T>? Therefore, if I want to pass as a type parameter, the class class Something{...}I will receive an error, but the transfer class Something implements Comparable<T>{...}will be ok? Please demystify this to me :( I have an exam for this tomorrow, and I can’t go to other things without grabbing it ... :(

+1
source share
2 answers

First of all, there are two things in Java:

  • common types like class GenericContainer<T>
  • general methods like your example public <T> method()

, , , . , .

, , , ,

public <T extends Comparable<T>> void myGenericMethod(...)

- , Java. . , .

T extends Comparable<T>, : , T myVariable, - . Java , , T, .

, ,

public <T> void method(T v1, T v2)

, v1 v2, , T - . v1.compareTo(v2) . , ?

:

public <T extends Comparable<T>> void method(T v1, T v2)

method() , Comparable<T>, . , compareTo(..), , , , .

+6

:

  • X extends Y X super Y "X is-a Y" "Y is-an X" . java , " ".
  • , , , , . , @Jack, < T extends Comparable< T > > , . ; , , .
  • "extends Comparable< T >" . Something , , , . , Something< Integer > si = new Something<>(); , Something< Object > so = new Something<>(); , Object Comparable< Object >.
+1

Source: https://habr.com/ru/post/1661369/


All Articles