passing List<String> to method expecting List<Object>
Solution 1
Try this:
public static void getMeListOfObjs(List<? extends Object> al) {
System.out.println(al.get(0));
}
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
String mys1 = "jon";
al.add(mys1);
getMeListOfObjs(al);
}
This wont compile, because List<String>
isn't match List<Object>
As @darijan pointed out the wildcard ? extends the type chack with all class that is descendant of it.
I recommend to read more about generics and wildcards
Solution 2
The code you provided works. I guess you want your al
list to be List<String>
. Then, you would have to make getMeListOfObjs
like this:
public static void getMeListOfObjs(List<? extends Object> al) {
System.out.println(al.get(0));
}
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
String mys1 = "jon";
al.add(mys1);
getMeListOfObjs(al);
}
Notice the differnce?
public static void getMeListOfObjs(List<? extends Object> al) {
The wildcard ?
changes any type that extends Object
, i.e. any object.
Solution 3
The example you have created does not create a List<String>
. You also use a List<Object>
you just add Strings to the Object list. So you essentially pass Object list, that's why it works. You can add any object the the object list including string. It works since the String extends Object.
damon
Updated on June 04, 2022Comments
-
damon almost 2 years
In
Page 112 of CHAPTER 5 GENERICS in the book - Effective Java
, these sentences appearsJust what is the difference between the raw type
List
and the parameterized typeList<Object>
...While you can pass aList<String>
to a parameter of type List, you can’t pass it to a parameter of typeList<Object>
I tried this
public static void getMeListOfObjs(List<Object> al){ System.out.println(al.get(0)); } public static void main(String[] args) { List<Object> al = new ArrayList<Object>(); String mys1 = "jon"; al.add(mys1); getMeListOfObjs(al); }
It runs without any error... Was that an error in book content? I am quoting from the second edition