简体   繁体   中英

Call java collections use an interface of an object instead of the object's class?

I want to call a method using a collection of objects that all implement the same interface. Is this possible?

public class GenericsTest {
    public void main() {
        ArrayList<Strange> thisWorks = new ArrayList<>();
        isAllStrange(thisWorks);
        ArrayList<Person> thisDoesNot = new ArrayList<>();
        isAllStrange(thisDoesNot);
    }

    public boolean isAllStrange(ArrayList<Strange> strangeCollection) {
        for (Strange object : strangeCollection) {
            if (object.isStrange())
                return true;
        }
        return false;
    }

    public interface Strange {
        public boolean isStrange();
    }

    public class Person implements Strange {
        public boolean isStrange() {
            return true;
        }
    }
}

You can do this using the <? extends Interface> <? extends Interface> notation:

public boolean isAllStrange(List<? extends Strange> strangeCollection) {
    for (Strange object : strangeCollection) {
        if (object.isStrange())
            return true;
    }
    return false;
}

Also, do not use ArrayList directly, instead use List . More of this:

Read about WildCard in Genrics.

You can do this using

<? extends Strange >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM