Search code examples
javaarraylistwildcardsubtyping

ArrayList of objects and abstract


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);
    }

}

Solution

  • You are asking for a Collection of AbstractList Objects, for example a list, filled with AbstractLists. Is that really what you intended?

    One way of solving it would be...

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

    ...this way, your method will only accept objects extending AbstractLists with any generic content.

    But as other commenters, posters and writers (J. Bloch: Effective Jave, p134+) have already and correctly pointed out, the better style would be simply trying something like this:

    void printCollection(AbstractList<?> c) {