0

I am trying to learn wildcards in Java. Here I am trying to modify the printCollection method so that it will only take a class which extends AbstractList. It shows the error in comment. I tried to use an ArrayList of objects, it works fine. I am using Java 7.

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

public class Subtype {
    void printCollection(Collection<? extends AbstractList<?>> c) {
        for (Object e : c) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        Subtype st= new Subtype();
        ArrayList<String> al = new ArrayList<String>();
        al.add("a");
        al.add("n");
        al.add("c");
        al.add("f");
        al.add("y");
        al.add("w");
        //The method printCollection(Collection<? extends AbstractList<?>>) in the type Subtype is not applicable for the 
        // arguments (ArrayList<String>)
        st.printCollection(al);
    }

}
4

2 に答える 2

2

AbstractLists で満たされたリストなど、AbstractList オブジェクトのコレクションを要求しています。それは本当にあなたが意図したものですか?

それを解決する1つの方法は...

<T extends AbstractList<?>> void printCollection(T c) {

...この方法では、メソッドは、一般的なコンテンツを持つ AbstractLists を拡張するオブジェクトのみを受け入れます。

しかし、他のコメンター、ポスター、ライター (J. Bloch: Effective Jave、p134+) がすでに正しく指摘しているように、より良いスタイルは単に次のようなことを試みることです:

void printCollection(AbstractList<?> c) {
于 2015-08-16T05:38:35.810 に答える
2

Collectionコードでは、パラメーターを実装する必要があり、拡張する要素を含める必要があると想定していますAbstractList

void printCollection(Collection<? extends AbstractList<?>> c)

必要なものを取得するには、次のように書くだけです。

void printCollection(AbstractList<?> c)
于 2015-08-16T06:00:00.680 に答える