0
What is generics in java?
why should we use generics? what is benefits of using? How to implement it?
1 Odpowiedź
+ 1
Generics allow you to have increased type safety at compile time. A common use is with Java Collections - rather than use List you use List<Object> where Object can be any class you want. So take List<String>, when we add or retrieve elements from this collection we can be assured the object is going to be String.
The whole topic can be quite complicated so can take a while to get your head around it. For example, if Bar is a subtype of Foo, it is not the case that List<Bar> is a subtype of List<Foo>. Further, generic type information is not available at runtime, this is known as type erasure and is one to look out for ;) check the official Java tutorials page for more info.
I've used some generics in the code, below line 40 roughly, to ensure different Number datatypes are used for various implementations, hopefully this example is useful
https://code.sololearn.com/cJx2F7FN6NKW/?ref=app