What is generics in java? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

What is generics in java?

why should we use generics? what is benefits of using? How to implement it?

23rd Jan 2018, 7:42 PM
Rahul Malkani
Rahul Malkani - avatar
1 Réponse
+ 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
23rd Jan 2018, 8:13 PM
Dan Walker
Dan Walker - avatar