How to create your own generic method (#25467)
The syntax how to create your own Generic method.
This commit is contained in:
committed by
Manish Giri
parent
773aae4fdc
commit
d5bf5a5bf3
@ -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
|
```java
|
||||||
import java.util.ArrayList;
|
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.
|
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
|
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.
|
and all existing libraries must be able to use generic types.
|
||||||
@ -136,3 +145,4 @@ 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)
|
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.
|
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.
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user