3

In Page 112 of CHAPTER 5 GENERICS in the book - Effective Java , these sentences appears

Just what is the difference between the raw type List and the parameterized type List<Object> ...While you can pass a List<String> to a parameter of type List, you can’t pass it to a parameter of type List<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


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.

4

5 回答 5

8

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

于 2013-06-17T08:28:38.710 回答
3

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.

于 2013-06-17T08:30:50.533 回答
1

您创建的示例不会创建List<String>. 您还可以使用List<Object>您只需将字符串添加到对象列表中。所以你基本上传递了对象列表,这就是它起作用的原因。您可以在对象列表中添加任何对象,包括字符串。它可以工作,因为字符串扩展了对象。

于 2013-06-17T08:27:56.550 回答
0

You are passing a List<Object> only. If your concern is that you have passed a String in the List<Object> that is perfectly fine because String IS-A Object.

Because even if you are putting a String as an element in the List<Object>, you are passing a List<Object> to the method.

于 2013-06-17T08:28:33.950 回答
0

The book is saying that you can do this:

List al = new ArrayList<String>();

(but Eclipse suggest you not to use raw types... "List is a raw type. References to generic type List should be parameterized")

but you can't do this:

List<Object> al = new ArrayList<String>();

because the compiler recognizes a type mismatch "cannot convert from ArrayList<String> to List<Object>"

于 2013-06-17T08:30:00.960 回答