ArrayList object C#

The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified [if you want to add or remove elements to/from an array, you have to create a new one]. While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

Create an ArrayList object called cars that will store strings:

import java.util.ArrayList; // import the ArrayList class ArrayList cars = new ArrayList[]; // Create an ArrayList object

If you don't know what a package is, read our Java Packages Tutorial.

Add Items

The ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add[] method:

import java.util.ArrayList; public class Main {   public static void main[String[] args] {     ArrayList cars = new ArrayList[];     cars.add["Volvo"];     cars.add["BMW"];     cars.add["Ford"];     cars.add["Mazda"];     System.out.println[cars];   } }

Try it Yourself »

Access an Item

To access an element in the ArrayList, use the get[] method and refer to the index number:

cars.get[0];

Try it Yourself »

Remember: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Item

To modify an element, use the set[] method and refer to the index number:

cars.set[0, "Opel"];

Try it Yourself »

Remove an Item

To remove an element, use the remove[] method and refer to the index number:

cars.remove[0];

Try it Yourself »

To remove all the elements in the ArrayList, use the clear[] method:

cars.clear[];

Try it Yourself »

ArrayList Size

To find out how many elements an ArrayList have, use the size method:

cars.size[];

Try it Yourself »

Loop Through an ArrayList

Loop through the elements of an ArrayList with a for loop, and use the size[] method to specify how many times the loop should run:

public class Main {   public static void main[String[] args] {     ArrayList cars = new ArrayList[];     cars.add["Volvo"];     cars.add["BMW"];     cars.add["Ford"];     cars.add["Mazda"];     for [int i = 0; i < cars.size[]; i++] {       System.out.println[cars.get[i]];     }   } }

Try it Yourself »

You can also loop through an ArrayList with the for-each loop:

public class Main {   public static void main[String[] args] {     ArrayList cars = new ArrayList[];     cars.add["Volvo"];     cars.add["BMW"];     cars.add["Ford"];     cars.add["Mazda"];     for [String i : cars] {       System.out.println[i];     }   } }

Try it Yourself »

Other Types

Elements in an ArrayList are actually objects. In the examples above, we created elements [objects] of type "String". Remember that a String in Java is an object [not a primitive type]. To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

Create an ArrayList to store numbers [add elements of type Integer]:

import java.util.ArrayList; public class Main {   public static void main[String[] args] {     ArrayList myNumbers = new ArrayList[];     myNumbers.add[10];     myNumbers.add[15];     myNumbers.add[20];     myNumbers.add[25];     for [int i : myNumbers] {       System.out.println[i];     }   } }

Try it Yourself »

Sort an ArrayList

Another useful class in the java.util package is the Collections class, which include the sort[] method for sorting lists alphabetically or numerically:

Sort an ArrayList of Strings:

import java.util.ArrayList; import java.util.Collections;  // Import the Collections class public class Main {   public static void main[String[] args] {     ArrayList cars = new ArrayList[];     cars.add["Volvo"];     cars.add["BMW"];     cars.add["Ford"];     cars.add["Mazda"];     Collections.sort[cars];  // Sort cars     for [String i : cars] {       System.out.println[i];     }   } }

Try it Yourself »

Sort an ArrayList of Integers:

import java.util.ArrayList; import java.util.Collections;  // Import the Collections class public class Main {   public static void main[String[] args] {     ArrayList myNumbers = new ArrayList[];     myNumbers.add[33];     myNumbers.add[15];     myNumbers.add[20];     myNumbers.add[34];     myNumbers.add[8];     myNumbers.add[12];     Collections.sort[myNumbers];  // Sort myNumbers     for [int i : myNumbers] {       System.out.println[i];     }   } }

Try it Yourself »



Arraylist class implements List interface and it is based on an Array data structure. It is widely used because of the functionality and flexibility it offers. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays. ArrayList is a resizable-array implementation of the List interface. It implements all optional list operations, and permits all elements, including null.

Table of Contents

1. Why ArrayList better than Array?
2. Create ArrayList
3. Add element
4. Change an element
5. Remove element
6. Loop ArrayList
7. ArrayList size
8. A simple example of ArrayList
9. Sort ArrayList
10. Methods of ArrayList class
11. Links of 50+ Tutorials and examples published on this website

Why ArrayList is better than Array?

The limitation with array is that it has a fixed length so if it is full you cannot add any more elements to it, likewise if there are number of elements gets removed from it the memory consumption would be the same as it doesn’t shrink.

On the other ArrayList can dynamically grow and shrink after addition and removal of elements [See the images below]. Apart from these benefits ArrayList class enables us to use predefined methods of it which makes our task easy. Let’s see the diagrams to understand the addition and removal of elements from ArrayList and then we will see the programs.

Adding Element in ArrayList at specified position:

Removing Element from ArrayList:

There is a list of several tutorials on ArrayList at the end of this guide, refer it to understand and learn ArrayList concept fully.

How to create an ArrayList?

We can create an ArrayList by writing a simple statement like this:

This statement creates an ArrayList with the name alist with type “String”. The type determines which type of elements the list will have. Since this list is of “String” type, the elements that are going to be added to this list will be of type “String”.

ArrayList alist=new ArrayList[];

Similarly we can create ArrayList that accepts int elements.

ArrayList list=new ArrayList[];

How to add elements to an ArrayList?

We add elements to an ArrayList by using add[] method, this method has couple of variations, which we can use based on the requirement. For example: If we want to add the element at the end of the List then simply do it like this:

alist.add["Steve"]; //This will add "Steve" at the end of List

To add the element at the specified location in ArrayList, we can specify the index in the add method like this:

alist.add[3, "Steve"]; //This will add "Steve" at the fourth position

Lets write the complete code:

import java.util.*; class JavaExample{ public static void main[String args[]]{ ArrayList alist=new ArrayList[]; alist.add["Steve"]; alist.add["Tim"]; alist.add["Lucy"]; alist.add["Pat"]; alist.add["Angela"]; alist.add["Tom"]; //displaying elements System.out.println[alist]; //Adding "Steve" at the fourth position alist.add[3, "Steve"]; //displaying elements System.out.println[alist]; } }

Output:

[Steve, Tim, Lucy, Pat, Angela, Tom] [Steve, Tim, Lucy, Steve, Pat, Angela, Tom]

Note: Since the index starts with 0, index 3 would represent fourth position not 3.

Change an element in ArrayList

We can use the set method to change an element in ArrayList. We provide the index and new element, this method then updates the element present at the given index with the new given element. In the following example, we have given the index as 0 and new element as “Lucy” in the set[] method, so the method updated the element present at the index 0 [which is the first element “Jim” in this example] with the new String element “Lucy”, which we can see in the output.

import java.util.ArrayList; public class JavaExample { public static void main[String[] args] { ArrayList names = new ArrayList[]; names.add["Jim"]; names.add["Jack"]; names.add["Ajeet"]; names.add["Chaitanya"]; names.set[0, "Lucy"]; System.out.println[names]; } }

Output:

We use remove[] method to remove elements from an ArrayList, Same as add[] method, this method also has few variations.

For example:

import java.util.*; class JavaExample{ public static void main[String args[]]{ ArrayList alist=new ArrayList[]; alist.add["Steve"]; alist.add["Tim"]; alist.add["Lucy"]; alist.add["Pat"]; alist.add["Angela"]; alist.add["Tom"]; //displaying elements System.out.println[alist]; //Removing "Steve" and "Angela" alist.remove["Steve"]; alist.remove["Angela"]; //displaying elements System.out.println[alist]; //Removing 3rd element alist.remove[2]; //displaying elements System.out.println[alist]; } }

Output:

[Steve, Tim, Lucy, Pat, Angela, Tom] [Tim, Lucy, Pat, Tom] [Tim, Lucy, Tom]

Iterating ArrayList

In the above examples, we have displayed the ArrayList elements just by referring the ArrayList instance, which is definitely not the right way to displays the elements. The correct way of displaying the elements is by using an advanced for loop like this.

import java.util.*; class JavaExample{ public static void main[String args[]]{ ArrayList alist=new ArrayList[]; alist.add["Gregor Clegane"]; alist.add["Khal Drogo"]; alist.add["Cersei Lannister"]; alist.add["Sandor Clegane"]; alist.add["Tyrion Lannister"]; //iterating ArrayList for[String str:alist] System.out.println[str]; } }

Output:

Gregor Clegane Khal Drogo Cersei Lannister Sandor Clegane Tyrion Lannister

ArrayList Size

We can use size[] method of ArrayList to find the number of elements in an ArrayList.

import java.util.ArrayList; public class JavaExample { public static void main[String[] args] { ArrayList numbers = new ArrayList[]; numbers.add[1]; numbers.add[7]; numbers.add[5]; numbers.add[6]; System.out.println["Number of elements in ArrayList: "+numbers.size[]]; } }

Output:

ArrayList Example in Java

This example demonstrates how to create, initialize, add and remove elements from ArrayList. In this example we have an ArrayList of type “String”. We have added 5 String element in the ArrayList using the method add[String E], this method adds the element at the end of the ArrayList.

We are then adding two more elements in the ArrayList using method add[int index, String E], this method adds the specified element at the specified index, index 0 indicates first position and 1 indicates second position.

We are then removing the elements “Chaitanya” and “Harry” from the ArrayList and then we are removing the second element of the ArrayList using method remove[int index]. Since we have specified the index as 1 [remove[1]], it would remove the second element.

import java.util.*; public class JavaExample { public static void main[String args[]] { /* Creating ArrayList of type "String" which means * we can only add "String" elements */ ArrayList obj = new ArrayList[]; /*This is how we add elements to an ArrayList*/ obj.add["Ajeet"]; obj.add["Harry"]; obj.add["Chaitanya"]; obj.add["Steve"]; obj.add["Anuj"]; // Displaying elements System.out.println["Original ArrayList:"]; for[String str:obj] System.out.println[str]; /* Add element at the given index * obj.add[0, "Rahul"] - Adding element "Rahul" at first position * obj.add[1, "Justin"] - Adding element "Justin" at second position */ obj.add[0, "Rahul"]; obj.add[1, "Justin"]; // Displaying elements System.out.println["ArrayList after add operation:"]; for[String str:obj] System.out.println[str]; //Remove elements from ArrayList like this obj.remove["Chaitanya"]; //Removes "Chaitanya" from ArrayList obj.remove["Harry"]; //Removes "Harry" from ArrayList // Displaying elements System.out.println["ArrayList after remove operation:"]; for[String str:obj] System.out.println[str]; //Remove element from the specified index obj.remove[1]; //Removes Second element from the List // Displaying elements System.out.println["Final ArrayList:"]; for[String str:obj] System.out.println[str]; } } Output: Original ArrayList: Ajeet Harry Chaitanya Steve Anuj ArrayList after add operation: Rahul Justin Ajeet Harry Chaitanya Steve Anuj ArrayList after remove operation: Rahul Justin Ajeet Steve Anuj Final ArrayList: Rahul Ajeet Steve Anuj

Sort ArrayList

We have a sort[] method in the Collections class. This class is is a part of java.util package. This method can be used to sort an ArrayList. In the following example we have sorted a list of String type alphabetically, however this method works on numeric list [such as Integer type ArrayList] as well.

import java.util.ArrayList; import java.util.Collections; public class JavaExample { public static void main[String[] args] { ArrayList fruits = new ArrayList[]; fruits.add["Orange"]; fruits.add["Apple"]; fruits.add["Banana"]; fruits.add["Pineapple"]; Collections.sort[fruits]; for [String str : fruits] { System.out.println[str]; } } }

Output:

Methods of ArrayList class

In the above example we have used methods such as add[] and remove[]. However there are number of methods available which can be used directly using object of ArrayList class. Let’s discuss few important methods of ArrayList class.

1] add[ Object o]: This method adds an object o to the arraylist.

obj.add["hello"];

This statement would add a string hello in the arraylist at last position.

2] add[int index, Object o]: It adds the object o to the array list at the given index.

obj.add[2, "bye"];

It will add the string bye to the 2nd index [3rd position as the array list starts with index 0] of array list.

3] remove[Object o]: Removes the object o from the ArrayList.

obj.remove["Chaitanya"];

This statement will remove the string “Chaitanya” from the ArrayList.

4] remove[int index]: Removes element from a given index.

obj.remove[3];

It would remove the element of index 3 [4th element of the list – List starts with o].

5] set[int index, Object o]: Used for updating an element. It replaces the element present at the specified index with the object o.

obj.set[2, "Tom"];

It would replace the 3rd element [index =2 is 3rd element] with the value Tom.

6] int indexOf[Object o]: Gives the index of the object o. If the element is not found in the list then this method returns the value -1.

int pos = obj.indexOf["Tom"];

This would give the index [position] of the string Tom in the list.

7] Object get[int index]: It returns the object of list which is present at the specified index.

String str= obj.get[2];

Function get would return the string stored at 3rd position [index 2] and would be assigned to the string “str”. We have stored the returned value in string variable because in our example we have defined the ArrayList is of String type. If you are having integer array list then the returned value should be stored in an integer variable.

8] int size[]: It gives the size of the ArrayList – Number of elements of the list.

int numberofitems = obj.size[];

9] boolean contains[Object o]: It checks whether the given object o is present in the array list if its there then it returns true else it returns false.

obj.contains["Steve"];

It would return true if the string “Steve” is present in the list else we would get false.

10] clear[]: It is used for removing all the elements of the array list in one go. The below code will remove all the elements of ArrayList whose object is obj.

obj.clear[];

Java ArrayList Tutorials

Here is the list of ArrayList tutorials published on beginnersbook.com.

ArrayList Basics

  • Initialize ArrayList
  • Loop ArrayList
  • Find length of ArrayList

Sorting

Add/Remove

Get/Search

Other Tutorials on ArrayList

Conversions:

Differences:

  • ArrayList vs Vector
  • ArrayList vs HashMap
  • ArrayList vs LinkedList

Reference

Video liên quan

Chủ Đề