java arraylist loop

java arraylist loop

To loop over the elements of an ArrayList in Java, you can use a for loop or an enhanced for loop.

Here is an example of how to loop over the elements of an ArrayList using a traditional for loop:

import java.util.ArrayList;

public class ArrayListLoopExample {

    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>();
        words.add("hello");
        words.add("world");
        words.add("goodbye");
        words.add("moon");

        for (int i = 0; i < words.size(); i++) {
            System.out.println(words.get(i));
        }
    }
}
Source:w‮uttual.ww‬ri.com

This code creates an ArrayList of strings called words and adds some elements to it. It then uses a traditional for loop to iterate over the elements of the list, starting from the first element (index 0) and ending at the last element (index words.size() - 1). The get() method is used to retrieve the element at each index.

Here is an example of how to loop over the elements of an ArrayList using an enhanced for loop:

for (String word : words) {
    System.out.println(word);
}

This code uses an enhanced for loop to iterate over the elements of the words list. The loop variable word is of the same type as the elements in the list, and it takes on the value of each element in turn.

Both of these loops will print the elements of the words list one by one, in the order they appear in the list.

You can also use an iterator to loop over the elements of an ArrayList. An iterator is an object that allows you to traverse a collection and perform operations on its elements. To get an iterator for an ArrayList, you can use the iterator() method of the ArrayList class.

Here is an example of how to loop over the elements of an ArrayList using an iterator:

import java.util.Iterator;

...

Iterator<String> it = words.iterator();
while (it.hasNext()) {
    String word = it.next();
    System.out.println(word);
}

This code gets an iterator for the words list using the iterator() method and assigns it to the it variable. It then uses a while loop to iterate over the elements of the list, using the hasNext() and next() methods of the iterator to check for and retrieve the next element.

Note that the iterator is a separate object from the list, and it maintains its own state as it traverses the elements of the list. This allows you to remove elements from the list using the remove method.

Created Time:2017-11-03 00:14:44  Author:lautturi