Java create array lists

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.

Читайте также:  Api binance github php

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); >> > 

Источник

Java Array of ArrayList, ArrayList of Array

Java Array of ArrayList, ArrayList of Array

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will learn how to create a Java array of ArrayList. We will also learn how to create an ArrayList of array elements.

Java Array of ArrayList

java array of arraylist, array of lists in java

Creating array of list in java is not complex. Below is a simple program showing java Array of ArrayList example.

import java.util.ArrayList; import java.util.List; public class JavaArrayOfArrayList < public static void main(String[] args) < Listl1 = new ArrayList<>(); l1.add("1"); l1.add("2"); List l2 = new ArrayList<>(); l2.add("3"); l2.add("4"); l2.add("5"); List[] arrayOfList = new List[2]; arrayOfList[0] = l1; arrayOfList[1] = l2; for (int i = 0; i < arrayOfList.length; i++) < Listl = arrayOfList[i]; System.out.println(l); > > > 

Notice that we can’t use generics while creating the array because java doesn’t support generic array. So if we try to use below code, it will produce compile time error as “Cannot create a generic array of List”.

List[] arrayOfList = new List[2]; 

Java ArrayList of Array

We can also create an array whose elements are a list. Below is a simple example showing how to create a list of array elements in java.

import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class JavaArrayListOfStringArray < public static void main(String[] args) < // List of String arrays Listlist = new ArrayList(); String[] arr1 = < "a", "b", "c" >; String[] arr2 = < "1", "2", "3", "4" >; list.add(arr1); list.add(arr2); // printing list of String arrays in the ArrayList for (String[] strArr : list) < System.out.println(Arrays.toString(strArr)); >> > 

java arraylist of array

Java ArrayList of Object Array

If you are not sure about the type of objects in the array or you want to create an ArrayList of arrays that can hold multiple types, then you can create an ArrayList of an object array. Below is a simple example showing how to create ArrayList of object arrays in java.

import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class JavaArrayListOfObjectArray < public static void main(String[] args) < // list of Object arrays to hold different types of array Listlist = new ArrayList(); String[] arr1 = < "a", "b", "c" >; String[] arr2 = < "1", "2", "3", "4" >; JavaArrayListOfObjectArray aa = new JavaArrayListOfObjectArray(); JavaArrayListOfObjectArray.A[] arr3 = < aa.new A("AA"), aa.new A("BB") >; list.add(arr1); list.add(arr2); list.add(arr3); // list holds different types of Object arrays, let's print them for (Object[] objArr : list) < System.out.println(Arrays.toString(objArr)); // iterating over the array and doing operation based on it's type for (Object obj : objArr) < // using instanceof keyword to find the Object type in the array if (obj instanceof String) < // doSomethingForStringObject(); >else if (obj instanceof JavaArrayListOfObjectArray.A) < // doSomethingForAObject(); >> > > /** * A sample class to use in arraylist of arrays * * @author pankaj * */ public class A < private String name; public A(String n) < this.name = n; >public String getName() < return this.name; >@Override public String toString() < return "A.class::"+this.name; >> > 
[a, b, c] [1, 2, 3, 4] [A.class::AA, A.class::BB] 

That’s all for creating an Array of ArrayList and ArrayList of Array in Java. You can checkout more core java examples from our GitHub Repository. Reference: Java Arrays

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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.

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.

Источник

ArrayList в Java

Java-университет

ArrayList — реализация изменяемого массива интерфейса List, часть Collection Framework, который отвечает за список (или динамический массив), расположенный в пакете java.utils. Этот класс реализует все необязательные операции со списком и предоставляет методы управления размером массива, который используется для хранения списка. В основе ArrayList лежит идея динамического массива. А именно, возможность добавлять и удалять элементы, при этом будет увеличиваться или уменьшаться по мере необходимости.

Что хранит ArrayList?

Только ссылочные типы, любые объекты, включая сторонние классы. Строки, потоки вывода, другие коллекции. Для хранения примитивных типов данных используются классы-обертки.

Конструкторы ArrayList

 ArrayList list = new ArrayList<>(); 
 ArrayList list2 = new ArrayList<>(list); 
 ArrayList list2 = new ArrayList<>(10000); 

Методы ArrayList

Ниже представлены основные методы ArrayList.

 ArrayList list = new ArrayList<>(); list.add("Hello"); 
 ArrayList secondList = new ArrayList<>(); secondList.addAll(list); System.out.println("Первое добавление: " + secondList); secondList.addAll(1, list); System.out.println("Второе добавление в середину: " + secondList); 
 Первое добавление: [Amigo, Hello] Второе добавление в середину: [Amigo, Amigo, Hello, Hello] 
 ArrayList copyOfSecondList = (ArrayList) secondList.clone(); secondList.clear(); System.out.println(copyOfSecondList); 
 System.out.println(copyOfSecondList.contains("Hello")); System.out.println(copyOfSecondList.contains("Check")); 
 // Первый способ for(int i = 0; i < secondList.size(); i++) < System.out.println(secondList.get(i)); >И цикл for-each: // Второй способ for(String s : secondList)

В классе ArrayList есть метод для обработки каждого элемента, который называется также, forEach. В качестве аргумента передается реализация интерфейса Consumer, в котором нужно переопределить метод accept():

 secondList.forEach(new Consumer() < @Override public void accept(String s) < System.out.println(s); >>); 

Метод accept принимает в качестве аргумента очередной элемент того типа, который хранит в себе ArrayList. Пример для Integer:

 ArrayList integerList = new ArrayList<>(); integerList.forEach(new Consumer() < @Override public void accept(Integer integer) < System.out.println(integer); >>); 
 String[] array = new String[secondList.size()]; secondList.toArray(array); for(int i = 0; i

Ссылки на дополнительное чтение

  1. Подробная статья о динамических массивах, а точнее — об ArrayList и LinkedList , которые выполняют их роль в языке Java.
  2. Статья об удалении элементов из списка ArrayList.
  3. Лекция о работе с ArrayList в схемах и картинках.

Источник

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