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.
You can call methods on the elements, which means that if the objects are mutable then they can be modified. But Strings are immutable. And so to get the effect you want you need to replace the element with a new object, which isn't possible using an enhanced for loop.
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
Syntax. The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:), then array or collection.
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);
}
}
}
If you implement Iterable you will get the desired behavior.
class MyList<T> implements Iterable<T> {
// your code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With