different ways of constructing an ArrayList

Java Static & Dynamic Data Structures, Declare different type of Arrays, Read Data, Print Arrays, Copy Arrays and Create Different Type of ArrayLists and conduct ArrayList Operations.
Post Reply
AyubHussain
Posts: 142
Joined: Fri Nov 23, 2018 2:48 am

different ways of constructing an ArrayList

Post by AyubHussain » Wed Dec 05, 2018 9:35 am

Explain the different ways of constructing an ArrayList?

ramya
Posts: 89
Joined: Fri Nov 23, 2018 2:55 am

Re: different ways of constructing an ArrayList

Post by ramya » Wed Dec 05, 2018 9:36 am

ArrayList can be created in 3 ways.

a) ArrayList() —> It creates an empty ArrayList with initial capacity of 10.

b) ArrayList(int initialCapacity) —> It creates an empty ArrayList with supplied initial capacity.

c) ArrayList(Collection c) —> It creates an ArrayList containing the elements of the supplied collection.

public class MainClass
{
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>(); //First Method

ArrayList<String> list2 = new ArrayList<String>(20); //Second Method

ArrayList<Integer> list3 = new ArrayList<Integer>(list1); //Third Method
}
}

AyubHussain
Posts: 142
Joined: Fri Nov 23, 2018 2:48 am

Re: different ways of constructing an ArrayList

Post by AyubHussain » Wed Dec 05, 2018 9:38 am

different ways of constructing an ArrayList:

ensureCapacity() method is used to increase the current capacity of an ArrayList. However, capacity of an ArrayList is automatically increased when we try to add more elements than the current capacity. To manually increase the current capacity, ensureCapacity() method is used.

public class MainClass
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();

//Now 'list' can hold 10 elements (Default Initial Capacity)

list.ensureCapacity(20);

//Now 'list' can hold 20 elements.
}
}

satyanarayanareddy
Posts: 24
Joined: Thu Jan 03, 2019 3:54 am

Re: different ways of constructing an ArrayList

Post by satyanarayanareddy » Mon Jan 21, 2019 4:47 am

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.

The important points about Java ArrayList class are:

Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.

Post Reply

Return to “Java Arrays and ArrayList”