How to Convert Array List to Array in Java - NareshIT

How to Convert Array List to Array in Java - NareshIT

Array List in Java

The ArrayList happens to be part of the collection framework and you will find it in java. util package. It’s a dynamic array in Java. If we talk of the speed then it is slower than the standard array, though it can be quite useful in various programming examples where you need loads of manipulations in the array as required. And you will find this class in java. util package. And you can contact us for your Java training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training.?

So, the list interface extends the collection and the ArrayList class implements the List interface.

Let’s have an example of how we can create an ArrayList. It’s a java program to demonstrate the working of the ArrayList in Java.

// Java program code for demonstrating
// how the arraylist works in Java
import java.io.*;
import java.util.*;
  
class Main {
    public static void main(String[] args)
    {
        // arraylist size
        int num = 5;
  
        // Declaration of Array list with size num
        ArrayList<Integer> arr1
            = new ArrayList<Integer>(num);
  
        //appending an element to to the end
        for (int a = 1; a<= num; a++)
            arr1.add(a);
  
        // element printing
        System.out.println(arr1);
  
        // remmoving element at index 2
        arr1.remove(2);
  
        // Displaying the ArrayList
        // after deletion
        System.out.println(arr1);
  
        // printing of element one after another
        for (int a = 0;a < arr1.size(); a++)
            System.out.print(arr1.get(a) + " ");
    }
}


        

Output:

input

[1, 2, 3, 4, 5]???????????????????????????????????????????????????????????????????????????????????????????????????????????????

[1, 2, 4, 5]??????????????????????????????????????????????????????????????????????????????????????????????????????????????????

1 2 4 5?


Now let's see how we can perform various operations on the ArrayList.

Below is the program on how we can add the element to the ArrayList. And also, we discuss how we can convert the ArrayList to the array, and then print out its element. let’s have the program below.

// How to add elements to an ArrayList

??

import java.util.*;

  

public class Main {

  

    public static void main(String args[])

    {

        ArrayList<String> arr2 = new ArrayList<>();

  

        arr2.add("Naresh");

        arr2.add("Technologies");

        arr2.add(1, "I");

         Object[] a=arr2.toArray();  

        System.out.println(a[1]);

        

    }

}        

Let’s now have in words how we can add an element to the ArrayList, We can implement the add() method. And this is overloaded through parameters and can perform numerous operations. The parameters are as below:

Add(object):

This is used for adding the element at the end of the ArrayList.


And the add( int index Object) is used for adding the element at a certain index in the ArrayList.

Also, we have the add(int index, Object): This is the method used for the addition of the element at a certain index in the ArrayList.


Now let's see how we can change the elements: Through the addition of the elements, we add to the ArrayList. Now suppose we want to change an element at an index. Let's have a program for this below:


import java.util.*;

  

public class Main {

  

    public static void main(String args[])

    {

    

        ArrayList<String> arr1 = new ArrayList<>();

  

        arr1.add("Hello");

        arr1.add("World of");

        arr1.add(2, "Engineers welcomes you");

  

        System.out.println("ArrayList Initially " + arr1);

  

        arr1.set(0, "Naresh");

         arr1.set(1, "I");

          arr1.set(2, "Technologies");

  

        System.out.println("ArrayList after updates" + arr1);

    }

}        

Output:

ArrayList Initially [Hello, World of, Engineers welcomes you]?????????????????????????????????????????????????????????????????

ArrayList after updates[Naresh, I, Technologies]????


3. Removing the elements:

For removing the elements in the ArrayList make use of the remove() method. It also comes overloaded for performing various operations depending on various parameters. Various forms of the remove method are as below:

Remove(Object): It’s the method that is applied for removing an object that is a part of the ArrayList. There can be numerous such objects, and in that case, the first object is removed.

Remove(int Index)

This method removes an object at the index mentioned. And all the elements move to the left for space-filling and the indices of each of the objects get updated.


// Java program for the removal of the element from the ArrayList

??

import java.util.*;

  

public class Main {

  

    public static void main(String args[])

    {

    

        ArrayList<String> arr1 = new ArrayList<>();

  

        arr1.add("Hello");

        arr1.add("World of");

        arr1.add(2, "Engineers welcomes you");

  

        System.out.println("ArrayList Initially " + arr1);

  

        arr1.set(0, "Naresh");

         arr1.set(1, "I");

          arr1.set(2, "Technologies");

  

        System.out.println("ArrayList after updates" + arr1);

    }

}        

Output:

Initially, The ArrayList is [Hello, All, World, and]???????????????????????????????????????????????????????????????????????????

After Removal at the index mentioned [Hello, All]??????????????????????????????????????????????????????????????????????????????

After Removal of the Object [Hello]???????????????????????????????????????????????????????????????????????????????????????????

???????????????????????????????????????


4. How to Iterate through an ArrayList:?

We have numerous methods for iterating all through it. And the best method is to make use of the for loop and the get() method for getting the element at various indexes.

// Java program for iteration through the ArrayList

??

import java.util.*;

  

public class Main {

  

    public static void main(String args[])

    {

        ArrayList<String> arr1

            = new ArrayList<>();

  

        arr1.add("Naresh");

        arr1.add("Technologies");

        arr1.add(1, "I");

  

        // making use of the get method and for loop

        for (int a = 0; a < arr1.size(); a++) {

  

            System.out.print(arr1.get(a) + " ");

        }

  

        System.out.println();

  

        // making use of the foreach loop

        for (String st1 : arr1)

            System.out.print(st1 + " ");

    }

}

        

Output:


Naresh I Technologies?????????????????????????????????????????????????????????????????????????????????????????????????????????

Naresh I Technologies?????

Various Essential Features:

The ArrayList is a class that inherits the AbstractList class and it implements the List Interface. We initialize it with the help of the size. And the size can be increased or decreased, and it's so as the collection grows or is reduced when the objects get removed from the collection.

We cannot use it as the primitive data types like char, int, and various such. We require the wrapper class in all such cases.

You can consider the ArrayList in Java much like the vector in C++.

You can never synchronize the ArrayList. It’s the equivalent class is Vector in Java.

We have the AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList as the classes that implement the list interface. And each of them has separate functionalities. The separate functionalities are as below:


AbstractList: This implements an unmodified list. And for that, we need to only extend the AbstractList class and we need implementation of the only get() and size methods.


CopyOnWriteArrayList: This implements the list interface, and it's an advanced version of ArrayList, and all the implementations are being implemented through the making of the list’s fresh copy.

AbstractSequentialList: This implements the AbstractCollection and the collection interface. It’s the class through which we implement the unmodified list, and for that, we need to extend the AbstractList class and need the implementation of the size() and the get() methods.


Let's now see how the ArrayList internally works. It’s a dynamic array and we are not required to mention the size during creation. It automatically increases or decreases dynamically, as we add and remove the items. However, the actual implementation of the library is quite complex.?


Various constructors in ArrayList:

For creating the ArrayList, we require creating an object of the ArrayList class of the array List. Various constructors in the class are as below:


ArrayList(): It’s the constructor for building an empty array list. If we want to create an empty ArrayList then we can use the below syntax:

ArrayList a1=new ArrayList();


ArrayList(Collection c): It’s the constructor that is used for building the ArrayList which we initialize with various elements that come from collection c. Now suppose we need to create an ArrayList ar1 that contains the elements of collection c, then we can make use of the below syntax: ArrayList ar1 = new ArrayList(col);


ArrayList (int capacity):

In this, we specify the initial capacity. Like: Suppose the initial size is N, and then suppose we make an ArrayList with it. It's done as below:

???????????????????ArrayList arr1= new ArrayList(N);

It’s also possible to make a generic ArrayList:

ArrayList <String> arr1 = new ArrayList <String>();


If you want to know more about the ArrayList then you can contact us. We offer a complete Java course for all. You can be a professional as well as you can be a layman.?

Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training , and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let's have a look at what you will get with this Java training package:

  • You need to pay a nominal fee.
  • You can choose any Java certification, as per your skills and interest.
  • You have the option to select from online and classroom training.
  • A chance to study at one of the best Java training institutes in India?
  • We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.
  • Naresh I technologies cater to one of the best Java training in India.
  • And a lot more is waiting for you.

Contact us anytime for your complete Java online training.

FAQ'S

1. Why would you need to convert an ArrayList to an array in Java?

There are several reasons why you might want to convert an ArrayList to an array:

  • Interoperability: Some methods or libraries may require an array as input.
  • Performance: In certain cases, arrays can offer better performance than ArrayLists, especially when dealing with primitive data types.
  • Specific use cases: There might be specific use cases where an array is more suitable than an ArrayList.

2. What are the different ways to convert an ArrayList to an array in Java?

There are two main ways to convert an ArrayList to an array:

  • Using the toArray() method: The toArray() method on an ArrayList returns an array containing all the elements of the list. You can specify the desired type of the array as an argument to this method.
  • Using the toArray(T[] a) method: This method takes an array as an argument and copies the elements from the ArrayList into the array. If the array is too small, a new array is created with the appropriate size.

3. What are the considerations when converting an ArrayList to an array?

When converting an ArrayList to an array, you should consider the following:

  • Type compatibility: Ensure that the type of the array you're creating is compatible with the elements in the ArrayList.
  • Array size: If the array you provide is too small, a new array will be created with the appropriate size.
  • Performance implications: While arrays can sometimes offer better performance than ArrayLists, the difference may be negligible for small lists.

For More Details Visit : Java Online Training

Register For Free Demo on UpComing Batches : https://nareshit.com/new-batches


要查看或添加评论,请登录

Naresh i Technologies的更多文章

社区洞察

其他会员也浏览了