The purpose of generics is not related to the fact that the generic parameter will be inferred to be the most specific type. The purpose of generic methods is to allow you to write a method that can work with any type and at the same time, maintain type safety.
Your printArray
method can not only take Number
as arguments, but also String
, SomeClass
, Object
and all sorts of reference types.
At this point you might ask "can't we just write Object
as the parameter types?" Sure with the type being Object
, the parameter will not only accept all reference types, but the primitives will also be accepted and boxed! So in this specific case, you don't necessarily have to use a generic method.
However, there are times when generic methods shine.
One of these occasions is when the methods work with generic types. For example, this is Optional.ofNullable
:
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
It creates a Nullable<T>
depending on whether the parameter is null. If this were not generic, it would have to return Optional<Object>
. Every time you want to call get
or orElse
, you need to cast the result to the type you want. If you made a mistake in one of the casts, a ClassCastException
might be thrown at runtime. But with generics, the compiler checks the types for you!
Here's another example:
public static <T> T first(List<T> list) { return list.get(0); }
Without generics, you would have to use the raw type List
and return an Object
. This again creates the problems of casting and reduced type safety.