Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating my own enhanced for loop

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.

like image 821
Otanan Avatar asked Feb 22 '14 06:02

Otanan


People also ask

Can you modify in enhanced for loop?

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.

What is 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.

Which syntax illustrates an 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.


2 Answers

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);
        }
    }
}
like image 61
Rohit Jain Avatar answered Sep 18 '22 02:09

Rohit Jain


If you implement Iterable you will get the desired behavior.

class MyList<T> implements Iterable<T> {
    // your code
}
like image 20
fastcodejava Avatar answered Sep 20 '22 02:09

fastcodejava