ilomambo
ilomambo

Reputation: 8350

Multiple iterators for class using Iterable

Having this class

public class MyClass {

   private List<Integer> list1 = new ArrayList<Integer>();
   private List<String> list2 = new ArrayList<String>();

   . . .
}

Is it possible to implement Iterable in the class in such a way that this code will work?:

MyClass a = new MyClass();

for(Integer i: a) {
   <do something with i>
}

for(String s: a) {
   <do something with s>
}

Let me clarify that I know how to iterate in other ways, even I know that I can create an iterator for each list type, I want to know if this specific form of iteration is possible.

Upvotes: 4

Views: 985

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

In order to get it working, you can implement the java.lang.Iterable interface and override the Iterable#iterator() method in the ClassA, but then only one of the loops will be compiling, because the iteration will be applied only over the one of the lists.

Better provide accessors for the lists and then do:

for(Integer i: a.getIntList()) {
   <do something with i>
}

for(String s: a.getStringList()) {
   <do something with s>
}

Upvotes: 3

Smutje
Smutje

Reputation: 18143

You can't provider a generic type with a list of bound types, so you have to decide for String or Integer - or you let MyClass expose the two collections through methods.

Upvotes: 1

Related Questions