I’m using the Pair class to store information about stadiums, i.e. name of the stadium and its capacity.
Let’s look at the first example. I create a list and fill it with instances of parameterized type Pair<String, Integer>(lines 1,2).If I explicitly create an instance of another parameterized type Pair<String, String>(line3), store it in a variable and try to add it to the list, the compiler throws an error, i.e. everything is as it should be(line 4). But if I remove lines 2,3 and create instance of Pair<String, String> directly in the add method(Second example) then the program is compiled and executed. Can anyone explain why the compiler did not throw an error?
first example(works as expected)
List<Pair<String, Integer>> stadiums = new ArrayList<>();
1. stadiums.add( new Pair("Bridgeforth Stadium", 25000));
2. stadiums.add( new Pair("Michigan Stadium", 109901));
3. Pair<String, String> stringPair = new Pair("Lane Stadium", "some str value");
4. stadiums.add(stringPair); // **Required type:Pair<String,Integer> Provided:Pair<String,String>**
second example(something wrong)
List<Pair<String, Integer>> stadiums = new ArrayList<>();
1. stadiums.add( new Pair("Bridgeforth Stadium", 25000));
2. stadiums.add( new Pair("Michigan Stadium", 109901));
5. stadiums.add( new Pair("Lane Stadium", "some str value"));
It seems to me that I need to create a variable of a parameterized type (as I indicated above) in order for the compiler to work correctly. But I would like to understand why this is so.
Mark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.