Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always use generics?

I created a unit test :

new Callable() {
@Override
public Object call() throws
         .....

I have received warning in Eclipse:

Callable is a raw type. References to generic type Callable<V> 
should be parameterized

Should I write code like:

new Callable<Object>()  

for eliminating warning, or not? It seems only junit test and there is no sense to add additional code... Thanks.

like image 730
user710818 Avatar asked Jul 02 '12 09:07

user710818


People also ask

When should you use generics?

The generic collections should be used whenever possible instead of classes such as ArrayList in the System. Collections namespace. You can create your own generic interfaces, classes, methods, events, and delegates. Generic classes may be constrained to enable access to methods on particular data types.

Are generics necessary?

Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.

Is it a good idea to use generics in collections?

By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

What is the disadvantages of using generics?

According to oracle documentation, the following points are the disadvantage of generics: Cannot instantiate Generic types with primitive types. Cannot create instances of type parameters. Cannot declare static fields whose types are type parameters.


1 Answers

Yes, it's a good practice to avoid raw types and use generic types. Using Callable<Object> makes it clear that the Callable is intended to return any kind of Object. Using Callable doesn't make that clear.

like image 52
JB Nizet Avatar answered Sep 23 '22 03:09

JB Nizet