Creating my own enhanced for loop
for-loop, generics, java
Solution
Is there a way to make my data type be recognized as an array so I could just pop it into a for loop as so?
Yes you can do that by implementing `Iterable` interface:
class MyList<T> implements Iterable<T> {
Object[] arr;
int size;
public MyList() {
arr = new Object[10];
}
public void add(T value) {
arr[size++] = value;
}
@Override
public Iterator<T> iterator() {
Iterator<T> iterator = new Iterator<T>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < size;
}
@Override
public T next() {
return (T)arr[index++];
}
@Override
public void remove() {
}
};
return iterator;
}
}
class Main {
public static void main(String[] args) {
MyList<String> myList = new MyList<String>();
myList.add("abc");
myList.add("AA");
for (String str: myList) {
System.out.println(str);
}
}
}
Problem
If I were to create my own data type in Java, I was wondering how I'd do it to make it "enhanced for loop compatible" if possible. For example: ``` System.out.println(object); //This implicitly calls the object's toString() method ``` Now, if I wanted to do a enhanced for loop with my own data type, how would I do it? ``` MyList<String> list = new MyList<>(); for(String s : list) System.out.println(s); ``` Is there a way to make my data type be recognized as an array so I could just pop it into a for loop as so? Do I extend some class? I'd rather not extend a premade class such as ArrayList or List, but maybe there's some other class like Comparable< T > Thank you.