user4136732
user4136732

Reputation:

What is the need for WildCard when Object type is available?

What is the need for Wildcard when object can be used as parameter in function definition which can accept any objects when it is compared to unbounded type..

package wildCards;

import java.util.ArrayList;
import java.util.List;

public class NeedForWildCard {
    public void processInput(List<String> values){

    //Insted of List<String> we could have used List<object> and what is the need for wildcard in here?

        for(String valueExtractor:values){
            System.out.println("values="+valueExtractor);
        }
    }
    public static void main(String[] args) {
        ArrayList<Integer> valuesInteger=new ArrayList<>();
        valuesInteger.add(100);
        valuesInteger.add(200);
        valuesInteger.add(300);
        NeedForWildCard example=new NeedForWildCard();
        example.processInput(valuesInteger);//valuesInteger is arguments since it is used in method call.
    }

}

Upvotes: 0

Views: 72

Answers (1)

Mohammad Najar
Mohammad Najar

Reputation: 2009

Let's say you have a method as following (with a wildcard argument Object list)

public void getList(List<Object> list){
    ... 
}

And then in a different method you do the following

List<String> strList = new ArrayList<String>();
getList(strList);

The second line will through a compilation error

The method getList(List<Object>) in the type TESTClass is not applicable for the arguments (List<String>)

You can't reference an object with a completely different object.

Upvotes: 3

Related Questions