User Tools

Site Tools


j1-3_loops

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
j1-3_loops [2024/12/03 00:35] – created appledogj1-3_loops [2024/12/03 00:42] (current) appledog
Line 130: Line 130:
 } }
 </Code> </Code>
 +
 +Although most loops by convention start at 0 and use something like i < 3, it's the same thing. These loops are the same as C loops more or less.
 +
 +== for-each
 +Java has for-each which is used for arrays, lists, and so on.
 +
 +<Code:Java>
 +public class Main {
 +    public static void main(String[] args) {
 +        int[] numbers = {10, 20, 30, 40, 50};
 +        
 +        for (int num : numbers) { // Iterates over each element in the array
 +            System.out.println("Number: " + num);
 +        }
 +    }
 +}
 +</Code>
 +
 +As you can see, this is a great way to iterate through lists.
 +
 +== iterators
 +Sometimes the reason why you want to for-each is to remove bad elements from a list. If you have a lot of memory you can just build a new list and delete the old one. But you can also use iterators, and that will let you remove items in-place. Otherwise they are pretty much equivalent in terms of looping through a list.
 +
 +<Code:Java>
 +import java.util.ArrayList;
 +import java.util.Iterator;
 +
 +public class Main {
 +    public static void main(String[] args) {
 +        ArrayList<String> list = new ArrayList<>();
 +        list.add("Apple");
 +        list.add("Banana");
 +        list.add("Cherry");
 +
 +        Iterator<String> iterator = list.iterator();
 +        while (iterator.hasNext()) {
 +            System.out.println(iterator.next());
 +        }
 +    }
 +}
 +</Code>
 +
 +
j1-3_loops.1733186110.txt.gz · Last modified: 2024/12/03 00:35 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki