+ 1
Java generics
Can anyone please explain me generics in java? What is a "container of type <T>"? I can pass different types of values and do the same operations on them? Or what? Need some help!
4 Answers
+ 17
Generics type can be used as a common type for all classes. In the following code, the printAll() method takes an array of object (any) and prints all elements of it. So we can pass any kind of object array to it. First I passed an array of Movie object, then Integer, then String. The method works fine for all. I don't have to write 3 different methods for 3 types.
Note 1: we can't pass int, char, boolean or any primitive values, it must be object. That's why I passed Integer instead of int.
Note 2: It's not necessary to use <T> or <Type>. You can use any non-preserved word. Just make sure to use that same name in the whole method.
https://code.sololearn.com/cSAr3bmoH3gK/?ref=app
+ 17
When you print or refer an object, it actually calls the toString() method. That's why you must write the toString() method definition just like this.
If you don't define any toString method, it'll call the toString method defined in Object class. (Object is super class of all classes). In that toSting method, the returned string follows this format:
class name @ memory address of that object
Just give a try, replace toString as tostring or something else in my code and run it. You'll get different output.
+ 1
thank you, but I can't see where do we call "toString" method, but it's called somewhere
0
I think I've got it, thank you