How to create your own generic method (#25467)

The syntax how to create your own Generic method.
pull/34717/head
Davor Beganović 2018-12-20 13:34:53 +01:00 committed by Manish Giri
parent 773aae4fdc
commit d5bf5a5bf3
1 changed files with 13 additions and 3 deletions

View File

@ -52,7 +52,7 @@ public class Example {
}
```
The syntax to create your own Generic class would be as follows.
**The syntax to create your own Generic class would be as follows.**
```java
import java.util.ArrayList;
@ -81,8 +81,17 @@ Note that the letter `T` is a placeholder, you could make that anything you like
throughout the class.
**The syntax to create your own Generic methods would be as follows.**
```java
public class GenericMethod {
public static <T> void printObject(T t){
System.out.println(t.toString());
}
}
```
Type Erasure in Java Generics
## Type Erasure in Java Generics
One of the downsides to introducing generics in Java 1.5 was how to ensure backward compatibility (ie) to make sure existing programs continue to work
and all existing libraries must be able to use generic types.
@ -135,4 +144,5 @@ public class GenericsErasure
When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for T is)
and verifies at compile time that you're doing the right thing, but the emitted code again just talks in terms of java.lang.Object - the compiler generates extra casts where necessary.
At execution time, a List<String> and a List<Date> are exactly the same the extra type information has been erased by the compiler.
At execution time, a List<String> and a List<Date> are exactly the same the extra type information has been erased by the compiler.