0

Why am i getting this error

public void getParameters(Map<String,Object> param){

}

public void test(){

    Map<String,String[]> testMap = new HashMap<String,String[]>();

    getParameters(testMap);  // type is not applicable error here

}

since i can pass String array to object like below. Can someone explain this please ?

public void getParameters(Object param){

}

public void test(){

    String[] testArray = new String[10];

    getParameters(testArray);

}
noname
  • 261
  • 1
  • 4
  • 11

3 Answers3

4

Java uses copy by values which means you can safely do this

String s = "Hello";
Object o = s;
o = 5; // `s` is not corrupted by this.

However you can't change something which references a different type.

Map<String, String> map = new HashMap<>();
map.put("hi", "hello");
Map<String, Object> map2 = (Map) map;
map2.put("hi", 5); // map now has an Integer value in it.

String s = map.get("hi"); // ClassCastException.

This is why you cannot safely pass an Map<String, String[]> as an Map<String, Object[]> because the latter would let you do

Object[] os = new Integer[1];
param.put("hi", os); // Your Map<String, String[]> is corrupted.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

String extends Object so that works but generics does not work that way.

Good explanation here http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html

Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71
0

You need a exact match of the type parameters of the relevant class. This means Map<String, String[]> is not assignable to Map<String, Object>. To make your code work use a wildcard:

public void getParameters(Map<String, ? extends Object> param){

}

or in this case simply

public void getParameters(Map<String, ?> param){

}
fabian
  • 80,457
  • 12
  • 86
  • 114