Pre Exam Test Practice (SSC | Banking | IAS | GATE | State Level | CLAT | Railways | Insurance | Teaching Exams | NDA | Defence | IES |State Exam )

Organizational Research By

Surprising Reserch Topic

when to use generic methods and when to use wild card

when to use generic methods and when to use wild card  using -'java,generics,wildcard'

I am reading about generic methods from OracleDocGenericMethod. I am pretty confused
about the comparison when it says when to use wild-card and when to use generic methods.
Quoting from the document.

interface Collection<E> {
    public boolean containsAll(Collection<?> c);
    public boolean addAll(Collection<? extends E> c);

We could have used generic methods here instead:

interface Collection<E> {
    public <T> boolean containsAll(Collection<T> c);
    public <T extends E> boolean addAll(Collection<T> c);
    // Hey, type variables can have bounds too!

  This tells us that the type argument is being used for polymorphism;
  its only effect is to allow a variety of actual argument types to be
  used at different invocation sites. If that is the case, one should
  use wildcards. Wildcards are designed to support flexible subtyping,
  which is what we're trying to express here.

Don't we think wild card like (Collection<? extends E> c); is also supporting kind of
polymorphism? Then why generic method usage is considered not good in this?

Continuing ahead, it states,

  Generic methods allow type parameters to be used to express
  dependencies among the types of one or more arguments to a method
  and/or its return type. If there isn't such a dependency, a generic
  method should not be used.

What does this mean?

They have presented the example

class Collections {
    public static <T> void copy(List<T> dest, List<? extends T> src) {

We could have written the signature for this method another way, without using wildcards at all:

class Collections {
    public static <T, S extends T> void copy(List<T> dest, List<S> src) {

The document discourages the second declaration and promotes usage of first syntax? What's the difference between the first and second declaration? Both seems to be doing the same thing?

Can someone put light on this area.

asked Sep 14, 2015 by LuizHTWYihln
0 votes

Related Hot Questions

Government Jobs Opening