1

Suppose I have a list of some class A defined as:

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. I just have list.

Rajat Mishra
  • 364
  • 1
  • 5
  • 19

2 Answers2

1

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:

    for(A a : (Iterable<A>) list) {
        // do stuff
    }

or when you need an Iterator iterating over elements of the 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.

Edit: This answer was edited thanks to helpful suggestions of Federico Peralta Schaffner and luk2302.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
  • 1
    You don't need the iterator. It's enough to cast to `Iterable`, then you could use a foreach loop: `for (A a : ((Iterable)list)) { /* use a */}` – fps Feb 28 '18 at 23:24
  • 1
    [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – luk2302 Mar 01 '18 at 08:01
  • @FedericoPeraltaSchaffner Thank you for commenting my answer. I edited it to cover what you've suggested - I guess I misunderstood OP's question a bit and thought that the iterator is needed here. – Przemysław Moskal Mar 01 '18 at 19:54
  • @luk2302 Thank you for providing this helpful link - I edited my answer to fill that gap in it. – Przemysław Moskal Mar 01 '18 at 19:58
  • But I don't know class A. – Rajat Mishra Mar 02 '18 at 12:08
  • @RajatMishra What do you mean by saying you don't know it? You used it in your sample code in your question and so did I. You can change it to `Integer`, `String` or whatever type of `ArrayList` you need (note that primitive types like `int` or `boolean` are not allowed - you need to use wrapper classes like `Integer` or `Boolean` instead). Simply change all occurrences of `A` in the code with the name of class you need to make it work with the type you need. – Przemysław Moskal Mar 02 '18 at 12:24
-1

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
}
Rajat Mishra
  • 364
  • 1
  • 5
  • 19