by BehindJava
What is an ArrayList Data Structure in Java
In this tutorial, we are going to learn about the ArrayList in detail.
ArrayList
- Have a look at ArrayList documentation which has detailed description.
- It uses a dynamic array to store the duplicate elements and maintains the insertion order.
- The ArrayList class maintains the insertion order and is non-synchronized which means it is not thread-safe.
- The elements stored in the ArrayList class can be randomly accessed.
- Cannot create the arrayList with primitive data types such as int, float, char etc.
Consider the following example.
import java.util.ArrayList;
public class ArrayListt {
public static void main(String args[]) {
int k = 1;
ArrayList a= new ArrayList();
System.out.println("array list" + a);
a.add("1");
a.add("NEW YORK");
a.add("PARIS");
a.add("SINGAPORE");
a.add("HONK KONG");
System.out.println("List size: " + a.size());
System.out.println("array list: " + a);
System.out.println("Is Paris present in List?: " + a.contains("PARIS"));
System.out.println("Location of NEW YORK in List: " + a.indexOf("NEW YORK"));
System.out.println("Is List Empty?: " + a.isEmpty());
a.add(1, "BEIZING");
a.remove("PARIS");
a.remove("NEW YORK");
System.out.println("array list after adding BEIZING and removing PARIS and NEW YORK:\n " + a);
//reverse ArrayList
System.out.println(a.toString());// returns string representation of array list
for (int i = 0; i < a.size(); i++)
System.out.print(a.get(i) + " ");
System.out.println();
a.set(0, "INDIA");
System.out.println(a);
int index = a.indexOf("SINGAPORE");
if (index == -1)
System.out.println("\nArrayList does not contain SINGAPORE: ");
else
System.out.println("\nArrayList contains SINGAPORE at index :" + index);
a.clear();
System.out.println("List is cleared: " + a);
}
}
Output:
array list[]
List size: 5
array list: [1, NEW YORK, PARIS, SINGAPORE, HONK KONG]
Is Paris present in List?: true
Location of NEW YORK in List: 1
Is List Empty?: false
array list after adding BEIZING and removing PARIS and NEW YORK:
[1, BEIZING, SINGAPORE, HONK KONG]
[1, BEIZING, SINGAPORE, HONK KONG]
1 BEIZING SINGAPORE HONK KONG
[INDIA, BEIZING, SINGAPORE, HONK KONG]
ArrayList contains SINGAPORE at index :2
List is cleared: []