Java Generics: Description and Methods

Since its inception, the Java language has undergone a lot of changes, which undoubtedly brought positive aspects to its functionality. One of these significant changes is the introduction of Java Generic or generalization. This functionality has made the language not only more flexible and versatile, but also much safer in terms of data type casting.

java generics description




, Java , Object. . Java Object. , Object . , .

Java Generics:

. Java Generic.

generic class java




, Pair. , T. , . : Pair<Integer> obj = new Pair< Integer >(). , T , , , T, V E.





: Java, , . : Pair<Integer> obj = new Pair<>().

, , . T , first second Integer.

, firstItem secondItem, , Integer . , , , . , : Pair<Integer> obj = new Pair<>(new Integer(1), new Integer(2)). setFirst setSecond. , , , getFirst getSecond Integer.

, . Pair .

java generic




, , . , Map, , . , – . , . , Pair : Pair<String, String> obj.





, , Java Pair. . , Pair. - . Java Generic .

. java generic . , , : Pair<Integer> obj1 Pair<Double> obj2. , obj1 = obj2 . Pair<T>, , , . Java Generic.

,

, , generic class java . , , , double long, . , Pair : Pair<int> obj. , Java -. , Pair , : Pair<Integer, Boolean> obj = new Pair<>(25, true).

. , : T first = new T(). , , , . .

, , java generic . , Pair . . , , . : class Pair<T extends Number>. , T Number .

. . Pair: class Pair<T, V extends T>. , , V , .

«» , extends super. class Pair<T super ArrayList> , ArrayList, , .

Generic Java

Java , . , .

generic java methods




As you can see in the figure above, there is nothing complicated in declaring a generic method. It is enough to put angle brackets in front of the type returned by the method and specify the type parameters in them.

In the case of the constructor, everything is done in the same way:

java generic type cleanup




In this case, angle brackets are preceded by the name of the constructor, since it does not return any value. The result of the work of both programs will be:

Integer

String




All Articles