我想使用所有实现相同接口的对象集合来调用方法.这可能吗?
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用<? extends Interface>表示法执行此操作:
public boolean isAllStrange(List<? extends Strange> strangeCollection) {
for (Strange object : strangeCollection) {
if (object.isStrange())
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
另外,请勿ArrayList直接使用,而是使用List.更多这样的:
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |