Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 485
Vishal Zanzrukia Avatar asked Jun 17 '14 16:06

Vishal Zanzrukia


People also ask

Is object a generic type?

Why Generics? The Object is the superclass of all other classes, and Object reference can refer to any object. These features lack type safety. Generics add that type of safety feature.

Why do we use generics instead of object?

Generics could be used to develop a better solution using a container that can have a type assigned at instantiation, otherwise referred to as a generic type, allowing the creation of an object that can be used to store objects of the assigned type.

What are generic objects?

Generic objects are structures for storing and interacting with data in an app. They are the primary type of entity through which the engine provides access to the components of an app.

What is the difference between generic class and generic method?

A generic class or structure can contain nongeneric procedures, and a nongeneric class, structure, or module can contain generic procedures. A generic procedure can use its type parameters in its normal parameter list, in its return type if it has one, and in its procedure code.


1 Answers

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.

like image 143
Tim B Avatar answered Sep 18 '22 15:09

Tim B