What is difference between Generic type and Object in method declaration?
Asked Answered
W

1

8

I am confused that which method Signature should I use for same purpose? Both are working fine for me.

1.

public <T, J> T findUniqueByCondition(String tableName, 
                                      String key, 
                                      J value, 
                                      Class<T> targetObject);

2.

public <T> T findUniqueByCondition(String tableName, 
                                   String key, 
                                   Object value, 
                                   Class<T> targetObject);

Which is best practice to use from above? I am really confused and can't find any advantage or dis-advantage of anyone? Is there any? If yes, please explain.

Walachia answered 17/6, 2014 at 16:53 Comment(0)
S
12

Like that there is no difference, for T you are using the type twice so you have a reason to use it but for J it is only used once.

If it really can be any object at all and you never use that type again then there is no reason to use generics for it. Generics allow you to take the return type and parameters of the method and link 2 or more of them together. They also allow you to link together multiple methods when using generics in a class definition.

Neither of those use cases applies here.

Seaman answered 17/6, 2014 at 16:55 Comment(3)
All in all, the difference is whether you can utilize the type inference, when compiler captures the actual type. +1.Sendal
I prefer the first option and avoid using Object.Georganngeorge
Hi.. @frostbite, why?Walachia

© 2022 - 2024 — McMap. All rights reserved.