java ArrayList demo
ArrayList in Java is a data structure that’s similar to array but with more convienient methods that you can use to add, remove, update elements from the ArrayList list easily. Unlike array that you have to defined the size of your data at the time of array declaration, ArrayList allows you to dynamically increase or decrease the size of the list by adding or removing the items from the list. The ArrayList demo below shows the usage of add, remove and set methods from the ArrayList.
[code language=”java”]
import java.util.ArrayList;
public class ArrayListDemo
{
public static void main(String[] args)
{
// Declaring an ArrayList for storing strings
ArrayList<String> str = new ArrayList<String>();
str.add("aaaaaa"); display(str);
str.add("bbbbbb"); display(str);
str.add("cccccc"); display(str);
str.add(2, "dddddd"); display(str);
str.remove(1); display(str);
str.set(0, "eeeeee"); display(str);
}
public static void display(ArrayList<String> str)
{
System.out.println("\nThe size of the list is " + str.size());
for(int x = 0; x < str.size(); ++x)
System.out.println("position " + x + " str: " + str.get(x));
}
}
[/code]
Output:
[code language=”text”]
The size of the list is 1
position 0 str: aaaaaa
The size of the list is 2
position 0 str: aaaaaa
position 1 str: bbbbbb
The size of the list is 3
position 0 str: aaaaaa
position 1 str: bbbbbb
position 2 str: cccccc
The size of the list is 4
position 0 str: aaaaaa
position 1 str: bbbbbb
position 2 str: dddddd
position 3 str: cccccc
The size of the list is 3
position 0 str: aaaaaa
position 1 str: dddddd
position 2 str: cccccc
The size of the list is 3
position 0 str: eeeeee
position 1 str: dddddd
position 2 str: cccccc
[/code]
Search within Codexpedia

Search the entire web
