ArrayList is a popular data structure in Java that provides a dynamic and resizable array, unlike traditional arrays that have a fixed size. ArrayLists are widely used in programming and can be easily converted from an array. In this article, we’ll look at the various ways of converting an array into an ArrayList in Java.

1. Using the Arrays.asList Method

The Arrays.asList method is the simplest and most straightforward way of converting an array into an ArrayList in Java. The method returns a fixed-size list that is backed by the original array, so changes to the ArrayList will reflect in the original array and vice-versa.

Here’s an example of how to use the Arrays.asList method:

String[] array = {"one", "two", "three"};
List<String> list = Arrays.asList(array);
System.out.println("ArrayList: " + list);

Output:

ArrayList: [one, two, three]

2. Using the Constructor

Another way of converting an array into an ArrayList is by using the ArrayList constructor. This method creates a new ArrayList and copies all the elements from the array into the new list.

Here’s an example of how to use the ArrayList constructor:

String[] array = {"one", "two", "three"};
List<String> list = new ArrayList<>(Arrays.asList(array));
System.out.println("ArrayList: " + list);

Output:

ArrayList: [one, two, three]

3. Using a Loop

You can also convert an array into an ArrayList by using a loop to iterate through the elements of the array and add them one by one to the ArrayList.

Here’s an example of how to use a loop to convert an array into an ArrayList:

String[] array = {"one", "two", "three"};
List<String> list = new ArrayList<>();
for (String str : array) {
  list.add(str);
}
System.out.println("ArrayList: " + list);

Output:

ArrayList: [one, two, three]

4. Using the Collections.addAll Method

The Collections.addAll method is another way of converting an array into an ArrayList in Java. This method adds all the elements from the array into the specified collection.

Here’s an example of how to use the Collections.addAll method:

String[] array = {"one", "two", "three"};
List<String> list = new ArrayList<>();
Collections.addAll(list, array);
System.out.println("ArrayList: " + list);

Output:

ArrayList: [one, two, three]

you’ll be able to convert an array into an ArrayList in no time.

It’s important to note that the methods discussed in this article are only applicable to arrays of objects, not primitive arrays. To convert a primitive array into an ArrayList, you’ll need to use a wrapper class such as Integer, Double, or Character.

Conclusion

In this article, we have covered the various ways of converting an array into an ArrayList in Java. You can choose the method that works best for you based on the requirements of your project. Whether you use the Arrays.asList method, the ArrayList constructor, a loop, or the Collections.addAll method,

Leave a Reply