- Java ArrayList add array example
- How to add Array to ArrayList in Java?
- 1) Using the addAll method of Collections class
- Example
- 2) Using the asList method of Arrays class and addAll method of ArrayList
- Example
- What is the preferred way to add array to ArrayList?
- About the author
- Add Multiple Items to Java ArrayList
- Java ArrayList
- Example
- Add Items
- Example
- Access an Item
- Example
- Change an Item
- Example
- Remove an Item
- Example
- Example
- ArrayList Size
- Example
- Loop Through an ArrayList
- Example
- Example
- Other Types
- Example
- Sort an ArrayList
- Example
- Example
- How to Add Elements to an Array in Java
- Adding elements to a Java array
- Method 1: Adding Elements to array by creating a new Java array
- Method 2: Adding Elements to an array in Java by using ArrayList
- Conclusion
- About the author
- Farah Batool
- Java add all items in array
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Java ArrayList add array example
Java ArrayList add array example shows how to add all elements of an array to ArrayList in Java. The example also shows how to add array to ArrayList using various ways.
How to add Array to ArrayList in Java?
There are various ways to add an array to ArrayList in Java.
1) Using the addAll method of Collections class
You can use addAll method of Collections class to add array to ArrayList.
This method adds all specified elements to the argument collection.
Example
2) Using the asList method of Arrays class and addAll method of ArrayList
You can use asList method of Arrays class to convert an array to the List object first.
This method returns a fixed size List object backed by the original argument array.
Once you get the List object, you can add the list object to the ArrayList using addAll method of ArrayList.
This method adds all elements of the specified collection at the end of the ArrayList object.
Example
What is the preferred way to add array to ArrayList?
Using addAll method of Collections class (approach 1) is preferred over using asList method of Arrays and addAll method of ArrayList class (approach 2) because it is faster in terms of performance under most implementation.
This example is a part of the ArrayList in Java tutorial and Array in Java tutorial.
Please let me know your views in the comments section below.
About the author
I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.
Add Multiple Items to Java ArrayList
Learn to add multiple items to an ArrayList in a single statement using simple-to-follow Java examples.
1. Using List.of() or Arrays.asList() to Initialize a New ArrayList
To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using either Arrays.asList() or List.of() methods. Both methods create an immutable List containing items passed to the factory method.
In the given example, we add two strings, “a” and “b”, to the ArrayList.
ArrayList arrayList = new ArrayList<>(Arrays.asList("a", "b")); //or ArrayList arrayList = new ArrayList<>(List.of("a", "b"));
2. Using Collections.addAll() to Add Items from an Existing ArrayList
To add all items from another collection to this ArrayList, we can use Collections.addAll() method that adds all of the specified items to the given list. Note that the items to be added may be specified individually or as an array.
ArrayList arrayList = new ArrayList<>(Arrays.asList("a", "b")); Collections.addAll(arrayList, "c", "d"); System.out.println(arrayList); //[a, b, c, d]
Alternatively, we can use ArrayList constructor that accepts a collection and initializes the ArrayList with the items from the argument collection. This can be useful if we add the whole collection into this ArrayList.
List namesList = Arrays.asList( "a", "b", "c"); ArrayList instance = new ArrayList<>(namesList);
3. Using Stream API to Add Only Selected Items
This method uses Java Stream API. We create a stream of elements from the first list, add a filter() to get the desired elements only, and then add the filtered elements to another list.
//List 1 List namesList = Arrays.asList( "a", "b", "c"); //List 2 ArrayList otherList = new ArrayList<>(Arrays.asList( "d", "e")); //Do not add 'a' to the new list namesList.stream() .filter(name -> !"a".equals(name)) .forEachOrdered(otherList::add); System.out.println(otherList); //[d, e, b, c]
In the above examples, we learned to add multiple elements to ArrayList. We have added all elements to ArrayList, and then we saw the example of adding only selected items to the ArrayList from the Java 8 stream API.
Java ArrayList
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:
Example
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:
Example
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListcars = new ArrayList(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars); > >
Access an Item
To access an element in the ArrayList , use the get() method and refer to the index number:
Example
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:
Example
Remove an Item
To remove an element, use the remove() method and refer to the index number:
Example
To remove all the elements in the ArrayList , use the clear() method:
Example
ArrayList Size
To find out how many elements an ArrayList have, use the size method:
Example
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:
Example
public class Main < public static void main(String[] args) < ArrayListcars = 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)); >> >
You can also loop through an ArrayList with the for-each loop:
Example
public class Main < public static void main(String[] args) < ArrayListcars = new ArrayList(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (String i : cars) < System.out.println(i); >> >
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:
Example
Create an ArrayList to store numbers (add elements of type Integer ):
import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListmyNumbers = new ArrayList(); myNumbers.add(10); myNumbers.add(15); myNumbers.add(20); myNumbers.add(25); for (int i : myNumbers) < System.out.println(i); >> >
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:
Example
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) < ArrayListcars = 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); >> >
Example
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) < ArrayListmyNumbers = 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); >> >
How to Add Elements to an Array in Java
Array is a group of same data type elements and is considered a fixed-size data structure. In Java, you cannot directly add elements to an array because the location next to the last element of the array is available in memory or not is not known. However, there are some other ways for adding elements to an array.
This blog will explain how to add an element to an array in Java. So let’s get started!
Adding elements to a Java array
In Java, you can add elements to an array:
Now, let’s check out the stated method one by one.
Method 1: Adding Elements to array by creating a new Java array
To add elements to an array in Java, first create an array then copy the existing array elements in the newly created array. After doing so, you can add new elements to it.
Example
In this example, firstly, we will create an integer array named numArray[ ] with the following values:
In the next step, we will create a new integer type array named newNumArray[ ] with a greater size of the existing array:
The element 77 is stored in the variable named appendValue, which we want to add:
For printing the array numArray[ ], use the System.out.println() method:
Now, copy the elements of array numArray[ ] in a newly created array newNumArray[ ] by using a for loop:
Then, insert the value that is stored in appendValue variable in the newNumArray[ ]:
Lastly, print the newNumArray[] elements:
The given output indicates that 77 is successfully added in the newNumArray[ ]:
Now, let’s check out the other method for adding elements to an array in Java.
Method 2: Adding Elements to an array in Java by using ArrayList
You can also utilize Java ArrayList to add elements to an array. It is considered ideal as ArrayList is a re-sizable array.
Example
First of all, we will create an integer type array named numArray[ ] with the following values:
Print array by using the System.out.println() method:
Create an ArrayList named newNumArrayList and pass the array in it by using the aslist() method:
Add the required element in the created ArrayList with the help of the add() method:
Now, we will convert this ArrayList into an array by using the toArray() method:
Finally, print the array with the appended element:
Output
We have provided all of the necessary information related to adding elements to an array in Java.
Conclusion
In Java, elements can be added to an array by using Array List or creating a new array. The best and most efficient method is utilizing the ArrayList for the mentioned purpose. To do so, convert the existing array into an ArrayList, add required elements, and then convert it to a normal array. ArrayList also takes less memory space. This blog discussed the methods of adding elements to an array in Java.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.
Java add all items in array
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter