Arraylist – In Java
import java.util.ArrayList;
public class Program1 {
public static void main(String[] args) {
ArrayList countries = new ArrayList();
countries.add("India");
countries.add("USA");
countries.add("China");
countries.add("Russia");
System.out.println(countries);
}
}
๐งพ Output:
[India, USA, China, Russia]
๐ก What is an ArrayList?
A resizable array in Java (from
java.util
package).Can store a list of objects (in this case, Strings).
Allows dynamic addition, removal, and retrieval of items.
๐ง Common Operations:
Operation | Example Code |
---|---|
Add an element | countries.add("Japan"); |
Get an element by index | countries.get(0); // India |
Set (replace) an element | countries.set(1, "UK"); |
Remove an element | countries.remove("China"); |
Size of the list | countries.size(); |
Loop through elements (for-each) | for(String c : countries) {} |
ย
๐ Example: Looping through the list:
ย
for (String country : countries)
{
System.out.println("Country: " + country);
}