I want to write a method which takes a Map as an parameter, which can contain any object as its value. I am trying to implement it using generics, but I am unable to implement it.
Below is the code that I have tried so far. This code as two methods: genericTest
, where I am trying to implement a generic solution, and nonGenericTest
, which is what I actually want to do with the generic solution but is implemented without using generics. Basically, the second method is the one which I want to convert to generics.
What am I doing wrong?
import java.util.Iterator;
import java.util.Map;
public class Test {
//V cannot be resolve to a type
public void genericTest(Map<String, V> params) {
}
public void nonGenericTest(Map<String, Object> params) {
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Object value = params.get(key);
if(value instanceof String){
String val1=(String) value;
// do something
}else if(value instanceof Integer){
Integer val1 = (Integer) value;
}
}
}
}
I am getting compiler error as shown in the code.
You've got two options:
Introduce V
as a type parameter to the class.
public class Test<V>
Introduce V
as a type parameter to that function.
public <V> void genericTest(Map<String, V> params)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments