Многомерный ArrayList в Java
Узнайте, как создавать многомерный Arraylist и работать с ним в Java.
1. Обзор
Создание многомерного ArrayList часто возникает во время программирования. Во многих случаях возникает необходимость создания двумерного ArrayList или трехмерного ArrayList .
В этом уроке мы обсудим, как создать многомерный ArrayList в Java.
2. Двумерный ArrayList
Предположим, мы хотим представить граф с 3 вершинами, пронумерованными от 0 до 2. Кроме того, предположим, что в графе есть 3 ребра (0, 1), (1, 2), и (2, 0), где пара вершин представляет ребро.
Мы можем представить ребра в виде 2-D ArrayList путем создания и заполнения ArrayList от ArrayList s.
Во-первых, давайте создадим новый 2-D ArrayList :
int vertexCount = 3; ArrayList> graph = new ArrayList<>(vertexCount);Далее мы инициализируем каждый элемент ArrayList другим ArrayList :
Наконец, мы можем добавить все ребра (0, 1), (1, 2), и (2, 0), к нашему 2-D ArrayList :
graph.get(0).add(1); graph.get(1).add(2); graph.get(2).add(0);
Давайте также предположим, что наш граф не является ориентированным графом. Итак, нам также нужно добавить края (1, 0), (2, 1), и (0, 2), к нашему 2-D ArrayList :
graph.get(1).add(0); graph.get(2).add(1); graph.get(0).add(2);
Затем, чтобы перебрать весь график, мы можем использовать двойной цикл for:
int vertexCount = graph.size(); for (int i = 0; i < vertexCount; i++) < int edgeCount = graph.get(i).size(); for (int j = 0; j < edgeCount; j++) < Integer startVertex = i; Integer endVertex = graph.get(i).get(j); System.out.printf("Vertex %d is connected to vertex %d%n", startVertex, endVertex); >>
3. Трехмерный ArrayList
В предыдущем разделе мы создали двумерный ArrayList. Следуя той же логике, давайте создадим трехмерный ArrayList :
Предположим, что мы хотим представить трехмерное пространство. Итак, каждая точка в этом трехмерном пространстве будет представлена тремя координатами, скажем, X, Y и Z.
В дополнение к этому, давайте представим, что каждая из этих точек будет иметь цвет: Красный, Зеленый, Синий или Желтый. Теперь каждая точка (X, Y, Z) и ее цвет могут быть представлены трехмерным ArrayList.
Для простоты предположим, что мы создаем трехмерное пространство (2 x 2 x 2). В нем будет восемь очков: (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), и (1, 1, 1).
Давайте сначала инициализируем переменные и 3-D ArrayList :
int x_axis_length = 2; int y_axis_length = 2; int z_axis_length = 2; ArrayList>> space = new ArrayList<>(x_axis_length);Затем давайте инициализируем каждый элемент ArrayList с помощью ArrayList> :
for (int i = 0; i < x_axis_length; i++) < space.add(new ArrayList>(y_axis_length)); for (int j = 0; j < y_axis_length; j++) < space.get(i).add(new ArrayList
space.get(0).get(0).add(0,"Red"); space.get(0).get(0).add(1,"Red");
Затем давайте установим синий цвет для точек (0, 1, 0) и (0, 1, 1):
space.get(0).get(1).add(0,"Blue"); space.get(0).get(1).add(1,"Blue");
И точно так же мы можем продолжать заполнять точки в пространстве для других цветов.
Обратите внимание, что точка с координатами (i, j, k) имеет информацию о цвете, хранящуюся в следующем 3-D ArrayList элемент:
Как мы видели в этом примере, переменная space является ArrayList . Кроме того, каждый элемент этого ArrayList является 2-D ArrayList (аналогично тому, что мы видели в разделе 2).
Обратите внимание, что индекс элементов в нашем пространство ArrayList представляет координату X, в то время как каждый 2-D ArrayList , присутствующий в этом индексе, представляет координаты (Y, Z).
4. Заключение
В этой статье мы обсудили, как создать многомерный ArrayList в Java. Мы видели, как мы можем представить график с помощью 2-D ArrayList . Кроме того, мы также исследовали, как представить трехмерные пространственные координаты с помощью трехмерного ArrayList .
В первый раз мы использовали ArrayList из ArrayList, в то время как во второй раз мы использовали ArrayList из 2-D ArrayList . Аналогично, чтобы создать N-мерный ArrayList, мы можем расширить ту же концепцию.
Полную реализацию этого руководства можно найти на GitHub .
2D ArrayList in Java
The following article provides an outline for 2D ArrayList in Java. In java array list can be two dimensional, three dimensional etc. The basic format of the array list is being one dimensional. Apart from one dimensional all other formats are considered to be the multi-dimensional ways of declaring arrays in java. Based on the number of dimensions expected to be added the number of arrays needs to be added. Moreover, an array list is very close to an array. An array list is a dynamic item. The same applies to a two-dimensional array list. These multidimensional arrays are very similar to the dynamic arrays where the size cannot be predefined.
import java.util.*; ArrayList arrayList = new ArrayList<> (); ArrayList list_name = new ArrayList<>(int capacity);
The above given is the syntax for array list creation in java, the array list needs to be created with the arraylist keyword as the first item. The array list forms the first item and then the data type of the array list needs to be declared. The array list data type needs to be followed by the list name. The name of the list value given here will be the actual list value expected. Next, the array list object needs to be created and this value is created with new as the arraylist.
How 2D ArrayList Works?
Some among the key characteristics of the array list are given below:
- The insertion order can be maintained by java ArrayList corresponding to the value insertion triggered.
- The two dimensional arrays allow duplicates to be stored in it. So the same value can be entered more than once in two dimensional arrays’ point of the case. This is another property which makes array list a close comparison to arrays. Array also has its own indices.
- Synchronization is not performed in this kind of array list items, this is one among the key items which differentiate the two dimensional ArrayList from the vectors, vectors are also elements java which does the same operation as two dimensional and multi-dimensional array lists, the key difference generated between these items in this statement. The capability to be non-synchronized.
- When compared to C++ elements these array lists are very closely related to vectors. The vectors in C++ and the array lists in java are intended to perform the same sought of operation in the background. This is another property which makes array list a close comparison to arrays. the array also has its own indices.
- Random access is a granted item in array lists. This means any specific item in the two dimensional array list can be reached through a pointer or a different reference. This is another property which makes array list a close comparison to arrays. Array also has its own indices. More predominantly the capability to reach each item of the array list without correspondence to the order is a key advantage in multidimensional and two-dimensional array lists. The space for the 0th row can be allocated with the use of a new keyword, this is done in this line. The 0th row also allows the store of 0 value as default. Next, the array list value is replaced with a new value. The replacement involves changing the value from 0 to 13. the value after array list changes is printed onto the console.
- The operations that control factors withinside the ArrayList are gradual as numerous transferring of factors desires to be performed if any detail is to be eliminated from the ArrayList.
- The ArrayList elegance cannot incorporate primitive kinds however best objects. In this case, we commonly name it as ‘ArrayList of objects. So in case you need to save integer kinds of elements, then you need to use the Integer item of the wrapper elegance and now no longer primitive kind int.
A sample diagrammatic representation of how two-dimensional array’s work in java, we can notice from the picture that each column is represented with the row and column level indices values. The first indice represents the row value whereas the second indices represent the column value. This is represented in the format of a[0][0] , a[0][1] etc.
Example of 2D ArrayList in Java
Given below is the example mentioned:
import java.util.*; public class Two_Dimensional_ArrayLists < public static void main(String args[]) < // The arraylist of 2d format will be declared here ArrayList> array_list = new ArrayList >(); // The space for the 0th row can be allocated with the use of new keyword, this is done in this line. The 0th row also allows the store of 0 value as default . array_list.add(new ArrayList()); // next the default value of 1 is changed to 13 here. array_list.get(1).add(0, 13); System.out.println("2D ArrayList… :"); System.out.println(array_list); > >
Explanation:
- The example explains the process of creating a 2-dimensional array list and then adding a value to the array list and then the value is attempted to be replaced with a different value. The first key process is to declare the headers for creating the two dimensional array list. In our case ‘import java.util.* ’. Next a class is declared. The declared class has the main function associated with it. The main function has the new array declared. So the declaration step for the array is placed with the main function.
- The array is declared as per the array list values. Next the add function is used for adding the values into the array list. The space for the 0th row can be allocated with the use of a new keyword, this is done in this line. The 0th row also allows the store of 0 value as default. Next the array list value is replaced with a new value. The replacement involves changing the value from 0 to 13. The value after arraylist changes is then printed onto the console.
Conclusion
The article shows the process of creating a two-dimensional array list. The syntax of creating the array list and key characteristics of the array list along with a suitable example is shown in this article.
Recommended Articles
This is a guide to 2D ArrayList in Java. Here we discuss the introduction, how 2D ArrayList works? and example respectively. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8
Вложенный ArrayList в Java
В Java ArrayList — это класс инфраструктуры коллекций Java, который предоставляет нам концепцию массивов с изменяемым размером. Это список массивов, в котором мы можем автоматически регулировать его емкость, добавляя или удаляя элементы. Поэтому он также известен как динамические массивы.
В этом руководстве мы обсудим и создадим вложенные списки массивов в Java.
Вложенный ArrayList — это список внутри списка. Из-за динамической природы ArrayLists мы можем добавить несколько измерений списка в соответствии с нашим требованием. Отдельные элементы такого списка сами являются списками.
Не забудьте импортировать java.util.Collections , поскольку он является частью структуры Collections . В следующем примере мы создаем вложенный список ArrayList.
import java.util.*; public class ABC public static void main(String args[]) ListArrayListInteger>> a = new ArrayList<>(); ArrayListInteger> al1 = new ArrayListInteger>(); ArrayListInteger> al2 = new ArrayListInteger>(); ArrayListInteger> al3 = new ArrayListInteger>(); al1.add(1); al1.add(2); al1.add(3); al2.add(4); al2.add(5); al2.add(6); al3.add(7); al3.add(8); al3.add(9); a.add(al1); a.add(al2); a.add(al3); for(ArrayList obj: a) ArrayListInteger> temp = obj; for(Integer num : temp) System.out.print(num + " "); > System.out.println(); > > >
В приведенном выше примере мы успешно создали двумерный вложенный список ArrayList и распечатали его. Мы создаем три отдельных ArrayList al1 , al2 , al3 и добавляем их как элементы в один ArrayList a . Обратите внимание, что конечный результат также напоминает матрицу.
Сопутствующая статья — Java ArrayList
Copyright © 2023. All right reserved