我想使用所有实现相同接口(interface)的对象集合来调用一个方法。这可能吗?
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;
}
}
}
最佳答案
您可以使用 <? extends Interface>
执行此操作符号:
public boolean isAllStrange(List<? extends Strange> strangeCollection) {
for (Strange object : strangeCollection) {
if (object.isStrange())
return true;
}
return false;
}
另外,不要使用 ArrayList
直接使用 List
.更多信息:
关于java - 调用 java 集合使用对象的接口(interface)而不是对象的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820160/