Looping Through an ArrayList in java
The size() method to define that how many times the loop should run. The looping through the principle of an ArrayList with a for loop
public class Main {
public static void main(String[] args) {
ArrayList<String> mobiles = new ArrayList<String>();
mobiles.add("Samsung");
mobiles.add("Apple");
mobiles.add("Nokia");
mobiles.add("Sony");
for (int i = 0; i < mobiles.size(); i++) {
System.out.println(mobiles.get(i));
}
}
}
You can also loop over an ArrayList with the for-each loop:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> mobiles = new ArrayList<String>();
mobiles.add("Samsung");
mobiles.add("Apple");
mobiles.add("Nokia");
mobiles.add("Sony");
for (String i : mobiles) {
System.out.println(i);
}
}
}
String in Java is an object. You must specify an equivalent wrapper class, To use other types, such as int,
Integer. For other primitive types,
For other primitive types, use:
Boolean for boolean,
Character for char,
Double for double, etc
Example
Create an ArrayList to store numbers (To Add elements of type Integer):
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> newNumbers = new ArrayList<Integer>();
newNumbers.add(100);
newNumbers.add(315);
newNumbers.add(120);
newNumbers.add(245);
for (int x : newNumbers) {
System.out.println(x);
}
}
}
Keywords: