j1-3_loops
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
j1-3_loops [2024/12/03 00:35] – created appledog | j1-3_loops [2024/12/03 00:42] (current) – appledog | ||
---|---|---|---|
Line 130: | Line 130: | ||
} | } | ||
</ | </ | ||
+ | |||
+ | 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. | ||
+ | |||
+ | < | ||
+ | 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(" | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | 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. | ||
+ | |||
+ | < | ||
+ | import java.util.ArrayList; | ||
+ | import java.util.Iterator; | ||
+ | |||
+ | public class Main { | ||
+ | public static void main(String[] args) { | ||
+ | ArrayList< | ||
+ | list.add(" | ||
+ | list.add(" | ||
+ | list.add(" | ||
+ | |||
+ | Iterator< | ||
+ | while (iterator.hasNext()) { | ||
+ | System.out.println(iterator.next()); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ |
j1-3_loops.1733186110.txt.gz · Last modified: 2024/12/03 00:35 by appledog