[英]How to iterate over a Java collection which is stored as Object type?
Suppose I have a list of some class A defined as:假设我有一个定义为 A 类的列表:
Object list = new ArrayList<A>();
I want to iterate over this.我想迭代这个。 Is it possible?
是否可以? If yes then how?
如果是,那么如何? Even if I find the type of list using reflections then also I won't get to class A. Also, note that I don't know what class A is.
即使我使用反射找到列表的类型,我也不会进入 A 类。另外,请注意,我不知道 A 类是什么。 I just have list.
我只有清单。
If you instantiate an ArrayList
the way that you've shown (you want it to be treated as Object
- this class doesn't allow iterating, classes implementing Iterable
interface provide this function), and then you need to iterate over its elements, you can cast this list
from Object
to Iterable
, that way iteration becomes available for list
:如果您按照您显示的方式实例化
ArrayList
(您希望将其视为Object
- 此类不允许迭代,实现Iterable
接口的类提供此功能),然后您需要迭代其元素,您可以施放此list
从Object
到Iterable
,这样反复可用的list
:
for(A a : (Iterable<A>) list) {
// do stuff
}
or when you need an Iterator iterating over elements of the list
:或者当你需要一个迭代器迭代
list
元素时:
Object list = new ArrayList<A> ();
Iterator<A> it = ((Iterable<A>)list).iterator();
You might want to have a look at Java API Documentation of to read more about Iterable interface here .您可能需要查看 Java API 文档以在此处阅读有关 Iterable 接口的更多信息。
Edit: This answer was edited thanks to helpful suggestions of Federico Peralta Schaffner and luk2302 .编辑:由于Federico Peralta Schaffner和luk2302 的有用建议,对这个答案进行了编辑。
I found a way to do so.我找到了一种方法。 I did something like this:
我做了这样的事情:
List<?> list1 = (List<?>) list;
now I can iterate as,现在我可以迭代为,
for(Object o : list1) {
// code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.