Java list dynamic size

Arrays are linear data structures which means that similar types of elements will be inserted as known in a continuous manner. Now as we know there is an issue with arrays that size needs to be specified at the time of declaration or taken from the user in java which constricts ourselves. Hence, there arise dynamic arrays in java in which entries can be added as the array increases its size as it is full. The size of the new array increases to double the size of the original array. Now all elements are retained in a new array which is in specified array domain size and the rest are added after them in the newly formed array. This array keeps on growing dynamically. 

Procedure: 

  1. First, we declared an array of types int with the private access specifier.
  2. Declare the count variable.
  3. Create a constructor that initializes the array of the given length.
  4. Here the magic comes with the method insert.
  5. First, before we insert the value it checks for the length of the array and count variable if both are of the same size then the array is said to be full.
  6. Then we create a new array whose size is twice the size of the previous array.
  7. Just initialized the new array with the previous array and reinitialized it back to the previous array.

Implementation: Creating an Array class that declares the int arr and int count. We just created an array whenever the array is full the array will be resized. 

Example

    public Array[int length] { arr = new int[length]; }

        for [int i = 0; i < count; i++] {

            System.out.print[arr[i] + " "];

    public void insert[int element]

        if [arr.length == count] {

            int newArr[] = new int[2 * count];

            for [int i = 0; i < count; i++] {

    public static void main[String[] args]

        Array numbers = new Array[3];


Article Tags :

The dynamic array is a variable size list data structure. It grows automatically when we try to insert an element if there is no more space left for the new element. It allows us to add and remove elements. It allocates memory at run time using the heap. It can change its size during run time. Dynamic arrays are two types:

The Vector class is used to create a generic dynamic array known as vectors that can hold objects of any type and any number. It is contained in java.util package. Arrays can be easily implemented as vectors.

Creating vectors:

Vectors are created like arrays as follows:

Vector vector_name = new Vector []; //declaring without sizeVector vector_name = new Vector [3];// declaring with size

Advantage of using Vectors:

  1. It is convenient to use vectors to store objects.
  2. A vector can be used to store a list of objects that may vary in size.
  3. We can add and delete objects from the list.

Example 1: string type

import java.util.*;public class VectorExample {    public static void main[String args[]] {        //Create a vector          Vector < String > vec = new Vector < String > [];        //Adding elements using add[] method of List          vec.add["Apple"];        vec.add["Banana"];        vec.add["Orange"];        vec.add["Mango"];        //Adding elements using addElement[] method of Vector          vec.addElement["Grapes"];        vec.addElement["Watermelon"];        vec.addElement["Gauva"];        System.out.println["Elements of vector: " + vec];    }}/*OUTPUT:Elements of vector: [Apple, Banana, Orange, Mango, Grapes, Watermelon, Gauva]

Example 2: integer type

import java.util.*;public class VectorExample {    public static void main[String args[]] {        //Create an empty Vector                Vector < Integer > num = new Vector [];        //Add elements in the vector          num.add[10];        num.add[20];        num.add[30];        num.add[20];        num.add[40];        //Display the vector elements          System.out.println["Values in vector: " + num];        //use remove[] method to delete the first occurence of an element          System.out.println["Remove first occourence of 20:" + num.remove[[Integer]20]];        //Display the vector elements afre remove[] method          System.out.println["Values in vector: " + num];;    }}/*OUTPUT:Values in vector: [10, 20, 30, 20, 40]Remove first occourence 20: trueValues in vector: [10, 30, 20, 40] */

An ArrayList class is a dynamic array, which is present in the java. util package. While built-in arrays have a fixed size, ArrayListcan change their size dynamically. Elements can be added and removed from an ArrayList whenever there is a need, helping the user with memory management.

The important points about Java Array List class are:

  • Java Array List class can contain duplicate elements.
  • Java Array List class maintains insertion order.
  • Java Array List allows random access because array works at the index basis.

Creating ArrayList:

Array List is created like arrays as follows:

syntax:

ArrayList arrayList= new ArrayList[];

import java.util.ArrayList;class Main {  public static void main[String[] args]{    // create ArrayList    ArrayList fruits = new ArrayList[]; // ArrayList with String type    // Add elements to ArrayList    fruits.add["apple"];    fruits.add["mango"];    fruits.add["banana"];    System.out.println["ArrayList: " + fruits];  }}/*OUTPUT:ArrayList: [apple, mango, banana] */

ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it.

ArrayList is part of Java’s collection framework and implements Java’s List interface.

Following are few key points to note about ArrayList in Java -

  • An ArrayList is a re-sizable array, also called a dynamic array. It grows its size to accommodate new elements and shrinks the size when the elements are removed.

  • ArrayList internally uses an array to store the elements. Just like arrays, It allows you to retrieve the elements by their index.

  • Java ArrayList allows duplicate and null values.

  • Java ArrayList is an ordered collection. It maintains the insertion order of the elements.

  • You cannot create an ArrayList of primitive types like int, char etc. You need to use boxed types like Integer, Character, Boolean etc.

  • Java ArrayList is not synchronized. If multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. You must explicitly synchronize access to an ArrayList if multiple threads are gonna modify it.

Creating an ArrayList and adding new elements to it

This example shows:

  • How to create an ArrayList using the ArrayList[] constructor.
  • Add new elements to an ArrayList using the add[] method.

import java.util.ArrayList; import java.util.List; public class CreateArrayListExample { public static void main[String[] args] { List animals = new ArrayList[]; animals.add["Lion"]; animals.add["Tiger"]; animals.add["Cat"]; animals.add["Dog"]; System.out.println[animals]; animals.add[2, "Elephant"]; System.out.println[animals]; } }

[Lion, Tiger, Cat, Dog] [Lion, Tiger, Elephant, Cat, Dog]

Creating an ArrayList from another collection

This example shows:

  • How to create an ArrayList from another collection using the ArrayList[Collection c] constructor.

  • How to add all the elements from an existing collection to the new ArrayList using the addAll[] method.

import java.util.ArrayList; import java.util.List; public class CreateArrayListFromCollectionExample { public static void main[String[] args] { List firstFivePrimeNumbers = new ArrayList[]; firstFivePrimeNumbers.add[2]; firstFivePrimeNumbers.add[3]; firstFivePrimeNumbers.add[5]; firstFivePrimeNumbers.add[7]; firstFivePrimeNumbers.add[11]; List firstTenPrimeNumbers = new ArrayList[firstFivePrimeNumbers]; List nextFivePrimeNumbers = new ArrayList[]; nextFivePrimeNumbers.add[13]; nextFivePrimeNumbers.add[17]; nextFivePrimeNumbers.add[19]; nextFivePrimeNumbers.add[23]; nextFivePrimeNumbers.add[29]; firstTenPrimeNumbers.addAll[nextFivePrimeNumbers]; System.out.println[firstTenPrimeNumbers]; } }

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Accessing elements from an ArrayList

This example shows:

  • How to check if an ArrayList is empty using the isEmpty[] method.
  • How to find the size of an ArrayList using the size[] method.
  • How to access the element at a particular index in an ArrayList using the get[] method.
  • How to modify the element at a particular index in an ArrayList using the set[] method.

import java.util.ArrayList; import java.util.List; public class AccessElementsFromArrayListExample { public static void main[String[] args] { List topCompanies = new ArrayList[]; System.out.println["Is the topCompanies list empty? : " + topCompanies.isEmpty[]]; topCompanies.add["Google"]; topCompanies.add["Apple"]; topCompanies.add["Microsoft"]; topCompanies.add["Amazon"]; topCompanies.add["Facebook"]; System.out.println["Here are the top " + topCompanies.size[] + " companies in the world"]; System.out.println[topCompanies]; String bestCompany = topCompanies.get[0]; String secondBestCompany = topCompanies.get[1]; String lastCompany = topCompanies.get[topCompanies.size[] - 1]; System.out.println["Best Company: " + bestCompany]; System.out.println["Second Best Company: " + secondBestCompany]; System.out.println["Last Company in the list: " + lastCompany]; topCompanies.set[4, "Walmart"]; System.out.println["Modified top companies list: " + topCompanies]; } }

Is the topCompanies list empty? : true Here are the top 5 companies in the world [Google, Apple, Microsoft, Amazon, Facebook] Best Company: Google Second Best Company: Apple Last Company in the list: Facebook Modified top companies list: [Google, Apple, Microsoft, Amazon, Walmart]

Removing elements from an ArrayList

This example shows:

  1. How to remove the element at a given index in an ArrayList | remove[int index]

  2. How to remove an element from an ArrayList | remove[Object o]

  3. How to remove all the elements from an ArrayList that exist in a given collection | removeAll[]

  4. How to remove all the elements matching a given predicate | removeIf[]

  5. How to clear an ArrayList | clear[]

import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class RemoveElementsFromArrayListExample { public static void main[String[] args] { List programmingLanguages = new ArrayList[]; programmingLanguages.add["C"]; programmingLanguages.add["C++"]; programmingLanguages.add["Java"]; programmingLanguages.add["Kotlin"]; programmingLanguages.add["Python"]; programmingLanguages.add["Perl"]; programmingLanguages.add["Ruby"]; System.out.println["Initial List: " + programmingLanguages]; programmingLanguages.remove[5]; System.out.println["After remove[5]: " + programmingLanguages]; boolean isRemoved = programmingLanguages.remove["Kotlin"]; System.out.println["After remove[\"Kotlin\"]: " + programmingLanguages]; List scriptingLanguages = new ArrayList[]; scriptingLanguages.add["Python"]; scriptingLanguages.add["Ruby"]; scriptingLanguages.add["Perl"]; programmingLanguages.removeAll[scriptingLanguages]; System.out.println["After removeAll[scriptingLanguages]: " + programmingLanguages]; programmingLanguages.removeIf[new Predicate[] { @Override public boolean test[String s] { return s.startsWith["C"]; } }]; System.out.println["After Removing all elements that start with \"C\": " + programmingLanguages]; programmingLanguages.clear[]; System.out.println["After clear[]: " + programmingLanguages]; } }

Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby] After remove[5]: [C, C++, Java, Kotlin, Python, Ruby] After remove["Kotlin"]: [C, C++, Java, Python, Ruby] After removeAll[scriptingLanguages]: [C, C++, Java] After Removing all elements that start with "C": [Java] After clear[]: []

Iterating over an ArrayList

The following example shows how to iterate over an ArrayList using

import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IterateOverArrayListExample { public static void main[String[] args] { List tvShows = new ArrayList[]; tvShows.add["Breaking Bad"]; tvShows.add["Game Of Thrones"]; tvShows.add["Friends"]; tvShows.add["Prison break"]; System.out.println["=== Iterate using Java 8 forEach and lambda ==="]; tvShows.forEach[tvShow -> { System.out.println[tvShow]; }]; System.out.println["\n=== Iterate using an iterator[] ==="]; Iterator tvShowIterator = tvShows.iterator[]; while [tvShowIterator.hasNext[]] { String tvShow = tvShowIterator.next[]; System.out.println[tvShow]; } System.out.println["\n=== Iterate using an iterator[] and Java 8 forEachRemaining[] method ==="]; tvShowIterator = tvShows.iterator[]; tvShowIterator.forEachRemaining[tvShow -> { System.out.println[tvShow]; }]; System.out.println["\n=== Iterate using a listIterator[] to traverse in both directions ==="]; ListIterator tvShowListIterator = tvShows.listIterator[tvShows.size[]]; while [tvShowListIterator.hasPrevious[]] { String tvShow = tvShowListIterator.previous[]; System.out.println[tvShow]; } System.out.println["\n=== Iterate using simple for-each loop ==="]; for[String tvShow: tvShows] { System.out.println[tvShow]; } System.out.println["\n=== Iterate using for loop with index ==="]; for[int i = 0; i { System.out.println["Name : " + user.getName[] + ", Age : " + user.getAge[]]; }]; } }

Name : Rajeev, Age : 25 Name : John, Age : 34 Name : Steve, Age : 29

Sorting an ArrayList

Sorting an ArrayList is a very common task that you will encounter in your programs. In this section, I’ll show you how to -

1. Sort an ArrayList using Collections.sort[] method

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayListCollectionsSortExample { public static void main[String[] args] { List numbers = new ArrayList[]; numbers.add[13]; numbers.add[7]; numbers.add[18]; numbers.add[5]; numbers.add[2]; System.out.println["Before : " + numbers]; Collections.sort[numbers]; System.out.println["After : " + numbers]; } }

Before : [13, 7, 18, 5, 2] After : [2, 5, 7, 13, 18]

2. Sort an ArrayList using ArrayList.sort[] method

import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class ArrayListSortExample { public static void main[String[] args] { List names = new ArrayList[]; names.add["Lisa"]; names.add["Jennifer"]; names.add["Mark"]; names.add["David"]; System.out.println["Names : " + names]; names.sort[new Comparator[] { @Override public int compare[String name1, String name2] { return name1.compareTo[name2]; } }]; names.sort[[name1, name2] -> name1.compareTo[name2]]; names.sort[Comparator.naturalOrder[]]; System.out.println["Sorted Names : " + names]; } }

# Output Names : [Lisa, Jennifer, Mark, David] Sorted Names : [David, Jennifer, Lisa, Mark]

3. Sort an ArrayList of Objects using custom Comparator

import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Person { private String name; private Integer age; public Person[String name, Integer age] { this.name = name; this.age = age; } public String getName[] { return name; } public void setName[String name] { this.name = name; } public Integer getAge[] { return age; } public void setAge[Integer age] { this.age = age; } @Override public String toString[] { return "{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public class ArrayListObjectSortExample { public static void main[String[] args] { List people = new ArrayList[]; people.add[new Person["Sachin", 47]]; people.add[new Person["Chris", 34]]; people.add[new Person["Rajeev", 25]]; people.add[new Person["David", 31]]; System.out.println["Person List : " + people]; people.sort[[person1, person2] -> { return person1.getAge[] - person2.getAge[]; }]; people.sort[Comparator.comparingInt[Person::getAge]]; System.out.println["Sorted Person List by Age : " + people]; Collections.sort[people, Comparator.comparing[Person::getName]]; System.out.println["Sorted Person List by Name : " + people]; } }

# Output Person List : [{name='Sachin', age=47}, {name='Chris', age=34}, {name='Rajeev', age=25}, {name='David', age=31}] Sorted Person List by Age : [{name='Rajeev', age=25}, {name='David', age=31}, {name='Chris', age=34}, {name='Sachin', age=47}] Sorted Person List by Name : [{name='Chris', age=34}, {name='David', age=31}, {name='Rajeev', age=25}, {name='Sachin', age=47}]

Synchronizing Access to an ArrayList

The ArrayList class is not synchronized. If multiple threads try to modify an ArrayList at the same time then the final result becomes not-deterministic because one thread might override the changes done by another thread.

The following example shows what happens when multiple threads try to modify an ArrayList at the same time.

import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class UnsafeArrayListExample { public static void main[String[] args] throws InterruptedException { List unsafeArrayList = new ArrayList[]; unsafeArrayList.add[1]; unsafeArrayList.add[2]; unsafeArrayList.add[3]; ExecutorService executorService = Executors.newFixedThreadPool[10]; Runnable task = [] -> { incrementArrayList[unsafeArrayList]; }; for[int i = 0; i

Chủ Đề