Add array to arraylist in java

Class ArrayList

Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)

The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(. ));

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Читайте также:  Самые быстрые сортировки python

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Источник

How to add arrays to ArrayList?

I have an int[3][3] array and it contains only 0 or 1 values, if the value is 1 I want to add the coordinates of this value in the ArrayList as int[2] array, but I don’t know why it always add the last 1-value coordinates, what’s the problem?

public static void main(String[] args) < Random random = new Random(); int[] coordinates = new int[2]; ArrayListarrayList = new ArrayList<>(); int[][] board = new int[3][3]; for (int i = 0; i < board.length; i++) < for (int j = 0; j < board[i].length; j++) < board[i][j] = random.nextInt(2); >> for (int i = 0; i < board.length; i++) < for (int j = 0; j < board[i].length; j++) < System.out.print(board[i][j] + " "); if (board[i][j] == 1)< coordinates[0] = i; coordinates[1] = j; arrayList.add(coordinates); >> System.out.println(); > System.out.println("coordinates of cells that contain 1 value"); for (int[] coordianate : arrayList) < for (int i = 0; i < coordianate.length; i++) < System.out.print(coordianate[i] + " "); >System.out.println(); > > 
1 0 1 1 1 0 1 1 0 coordinates of cells that contain 1 value 2 1 2 1 2 1 2 1 2 1 2 1 

3 Answers 3

You need to create new coordinates array for each i , j pair you want to place in your list. For now you are placing same array multiple times which remembers last set pair.

In other words you need to

You need to create a new coordinate object every time you add it:

Otherwise you will add the same object multiple times and modify it each time so only the last coordinate remains.

If you make it a habit to use narrow scoped (temporary) variables, this typically comes naturally as you do not drag state around outside of loops.

If you are putting Points into an ArrayList, I suggest you create a Point object that takes coordinates. Please refer to the code below. Sorry for the lengthy reply.

import java.util.ArrayList; import java.util.Arrays; public class SomeClass < static class Point < int[] coordinates; public Point(int x, int y) < this.coordinates = new int[2]; this.coordinates[0] = x; this.coordinates[1] = y; >public Point() < this(0,0); >public Point(int[] coordinates) < this.coordinates = coordinates; >> public static void main(String[] args) < SomeClass myClass = new SomeClass(); Point a = new Point(); Point b = new Point(5,5); Point c = new Point(new int[]); ArrayList arr = new ArrayList(); // adding arr.add(a); arr.add(b); arr.add(c); // retrieve one object int index = 0; Point retrieved = arr.get(index); System.out.println("Retrieved coordinate: " + Arrays.toString(retrieved.coordinates)); retrieved.coordinates[0] = 15; retrieved.coordinates[1] = 51; System.out.println("After change, retrieved coordinate: " + Arrays.toString(retrieved.coordinates)); System.out.println("After change, accessing arraylist index: " + Arrays.toString(arr.get(index).coordinates)); // we received a pointer to the array // changed values are automatically reflected in the ArrayList > > 

These are the values you will get.

Retrieved coordinate: [0, 0] After change, retrieved coordinate: [15, 51] After change, accessing arraylist index: [15, 51] 

Источник

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.

Источник

How to Convert an array to ArrayList in java

In the last tutorial, you learned how to convert an ArrayList to Array in Java. In this guide, you will learn how to convert an array to ArrayList.

Method 1: Conversion using Arrays.asList()

ArrayList arraylist= new ArrayList(Arrays.asList(arrayname));

Example:
In this example, we are using Arrays.asList() method to convert an Array to ArrayList.

Here, we have an array cityNames with four elements. We have converted this array to an ArrayList cityList . After conversion, this arraylist has four elements, we have added two more elements to it using add() method.

In the end of the program, we are printing the elements of the ArrayList, which displays 6 elements, four elements that were added to arraylist from array and 2 new elements that are added using add() method.

import java.util.*; public class JavaExample < public static void main(String[] args) < // Array declaration and initialization String cityNames[]=; // Array to ArrayList conversion ArrayList cityList= new ArrayList(Arrays.asList(cityNames)); // Adding new elements to the list after conversion cityList.add("Chennai"); cityList.add("Delhi"); //print ArrayList elements using advanced for loop for (String str: cityList) < System.out.println(str); >> >
Agra Mysore Chandigarh Bhopal Chennai Delhi

Method 2: Conversion using Collections.addAll() method

Collections.addAll() method adds all the array elements to the specified collection. We can call the Collections.addAll method as shown below. It works just like Arrays.asList() method however, it is much faster. Conversion using Collections.addAll() method gives better performance compared to asList() method.

String array[]=; ArrayList arraylist = new ArrayList(); Collections.addAll(arraylist, array);
Collections.addAll(arraylist, new Item(1), new Item(2), new Item(3), new Item(4));
import java.util.*; public class JavaExample < public static void main(String[] args) < // Array declaration and initialization*/ String array[]=; //ArrayList declaration ArrayList arraylist= new ArrayList(); // conversion using addAll() Collections.addAll(arraylist, array); //Adding new elements to the converted List arraylist.add("String1"); arraylist.add("String2"); //print ArrayList for (String str: arraylist) < System.out.println(str); >> >
Hi Hello Howdy Bye String1 String2

Method 3: Convert Array to ArrayList manually

This program demonstrates how to convert an Array to ArrayList without using any predefined method such as asList() and addAll() .
The logic of this program is pretty simple, we are iterating the array using for loop and adding the element to the ArrayList on every iteration of the loop. This means, in the first iteration, the first element of the array is added to the ArrayList, in the second iteration second element gets added and so on.

To read the whole array, we are using arr.length property. The array.length property returns the number of elements in the array. In the following example, since the array contains four elements, this will return 4. Thus we can say that the for loop runs from i=0 to i

In the end, we are displaying ArrayList elements using advanced for loop.

import java.util.*; public class JavaExample < public static void main(String[] args) < //ArrayList declaration ArrayListarrayList= new ArrayList(); //Initializing Array String array[] = ; /* array.length returns the number of * elements present in array*/ for(int i =0;i //print ArrayList content for(String str: arrayList) < System.out.println(str); >> >

Recommended Articles:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

In Method 2 ,
can’t we use this method to convert array to arraylist :
arraylist.addAll(array); as we have used it earlier for list :
arraylist.addAll(list);

Hello,
The method to convert an array to ArrayList using Arrays.asList() works well for any String array, but not with Integer type arrays. Please help.
Thanks

If you are using the array as “int[] obj=new int[x];” then it will not work because the array list can be created for the Integer class not the int class so it will return a type mismatch error. so take the array as Integer[] obj=new Integer[x];

Источник

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.

Источник

Оцените статью