Nested arraylist in java

Многомерный ArrayList в Java

Создание многомерного ArrayList часто возникает во время программирования. Во многих случаях необходимо создать двумерный ArrayList или трехмерный ArrayList .

В этом руководстве мы обсудим, как создать многомерный ArrayList в Java.

2. Двумерный список массивов ​

Предположим, мы хотим представить граф с 3 вершинами, пронумерованными от 0 до 2. Кроме того, предположим, что в графе есть 3 ребра (0, 1), (1, 2) и (2, 0), где пара вершин представляет ребро.

Мы можем представить ребра в 2-D ArrayList , создав и заполнив ArrayList из ArrayList s.

Во-первых, давайте создадим новый 2-D ArrayList :

 int vertexCount = 3;   ArrayListArrayListInteger>> graph = new ArrayList>(vertexCount); 

Далее мы инициализируем каждый элемент ArrayList другим ArrayList :

 for(int i=0; i  vertexCount; i++)    graph.add(new 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 :

Предположим, что мы хотим представить трехмерное пространство. Таким образом, каждая точка в этом трехмерном пространстве будет представлена тремя координатами, скажем, 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;   ArrayListArrayListArrayListString>>> space = new ArrayList>(x_axis_length); 

Затем давайте инициализируем каждый элемент ArrayList с помощью ArrayList> :

 for (int i = 0; i  x_axis_length; i++)    space.add(new ArrayListArrayListString>>(y_axis_length));   for (int j = 0; j  y_axis_length; j++)    space.get(i).add(new ArrayListString>(z_axis_length));   >   > 

Теперь мы можем добавлять цвета к точкам в пространстве. Добавим красный цвет для точек (0, 0, 0) и (0, 0, 1):

 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 является двумерным 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 .

Источник

Nested ArrayList in Java

Nested ArrayList in Java

In Java, ArrayList is a class of Java Collections framework that provides us with the concept of resizable arrays. It is a list of arrays where we can automatically adjust its capacity by adding or removing elements. It is therefore also known as Dynamic Arrays.

This tutorial will discuss and create nested ArrayLists in Java.

A nested ArrayList is a list within a list. Due to the dynamic nature of ArrayLists, we can have multiple dimensions of the list added on as per our requirement. Individual elements of such a list are lists themselves.

Remember to import the java.util.Collections as it is part of the Collections framework. We create a nested ArrayList in the following example.

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

In the above example, we have successfully created a two-dimensional nested ArrayList and print it. We create three individual ArrayLists al1 , al2 , al3 , and add them as elements to a single ArrayList a . Note that the final result also resembles a matrix.

Related Article — Java ArrayList

Copyright © 2023. All right reserved

Источник

Programming Blog

Welcome To Programming Tutorial. Here i share about Java Programming stuff. I share Java stuff with simple examples.

Search This Blog

How to Create Nested ArrayList in Java | 2D ArrayList — BlogonCode

Multi-Dimensional ArrayList in Java | Creating and Store Elements in Nested ArrayList

Multi-Dimensional ArrayList in Java | Creating and Store Elements in Nested ArrayList

In Java, ArrayList is Class of Java Collections framework that stores elements with resizable arrays. ArrayList is also called Dynamic Arrays.

Often times, We need to store data in dynamic array rather than static array. So in this tutorial we will seen how we can create, store and print nested or two dimensional arraylist elements.

We will seen two approach for storing nested elements in ArrayList.

  1. Creating Nested ArrayList with Static Elements
  2. Creating Nested ArrayList with Dynamic Elements using Scanner Class

Learn more about ArrayList class :

Example 1 : Nested ArrayList with Static Elements

import java.util.ArrayList;
import java.util.List;

public class NestedArrayList

public static void main(String[] args)

List> outerList = new ArrayList<>();

ArrayList al1 = new ArrayList();
ArrayList al2 = new ArrayList();

Now lets see how to store user defined elements in nested arraylist

Example 2 : Nested ArrayList with Dynamic (User defined) Elements

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class NestedArrayList

public static void main(String[] args)

Scanner sc = new Scanner(System.in);
System.out.println(«Enter Size of ArrayList»);
int size = sc.nextInt();
List> outerList = new ArrayList>();
List innerList = null;
System.out.println(«Insert Elements»);

for (int i = 0; i < size; i++) innerList = new ArrayList();
for (int j = 0; j < size; j++) innerList.add(sc.nextInt());
>
outerList.add(innerList);
>

Enter Size of ArrayList
2
Insert Elements
1 2 3 4
[[1, 2], [3, 4]]________________________

Enter Size of ArrayList
4
Insert Elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

RECOMMENDED ARTICLES :

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Labels

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Comments

Post a Comment

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as: 0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1] There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Diagonal Difference in Java | Find difference between sums of two diagonals | HackerRank problem

Java Solution for HackerRank Diagonal Difference problem Problem Description : Given a square matrix, calculate the absolute difference between the sums of its diagonals. For example, the square matrix arr is shown below: 1 2 3 4 5 6 9 8 9 The left to right diagonal = 1 + 5 + 9 = 15 The right to left diagonal = 3 + 5 + 9 = 17 Their absolute difference is | 15 — 17 | = 2. See full description : Diagonal Difference HackerRank Problem Description Sample Input : Row and Column Size : 3 2 4 6 1 3 5 7 8 -9 Sample Output : 2 Explanation : left to right diagonal = 2 + 3 — 9 = -4. The right to left diagonal = 6 + 3 + 7 = 16. So the absolute difference is | -4 — 16 = 20 | Lest see solution and its explanation. Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; im

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Welcome To Programming Tutorial. Here i share about Java Programming stuff. I share Java stuff with simple examples.

Labels

  • Automatic Type Promotion 1
  • BiConsumer 1
  • BigInteger 2
  • Binary Search 3
  • BiPredicate 1
  • coding 3
  • Coding Questions 1
  • Collection 1
  • Collection Framework 3
  • Comparable Interface 1
  • Comparator Interface 3
  • Competitive Programming 1
  • Consumer 1
  • Core Java 4
  • Custom Exception 1
  • DevOps 1
  • Download File 1
  • equals() 1
  • Exception Handling 5
  • File 2
  • filter() 1
  • final keyword 1
  • Free Courses 2
  • Functinal Interface 1
  • GET Request 1
  • Git 1
  • HackerRank 59
  • hashCode() 1
  • HashSet 1
  • HttpURLConnection 1
  • Immutable Class 2
  • Inheritance 1
  • Inner Class 5
  • Interface 2
  • Interview Questions 4
  • Iterator 2
  • Java 160
  • java example 7
  • Java Map 1
  • Java8 20
  • JavaScript 4
  • Jenkins 2
  • Jenkins Pipeline 2
  • JPA 3
  • JSONArray 1
  • JSONObject 1
  • Lambda Expression 1
  • LeetCode 27
  • Linked List 4
  • LinkedHashSet 1
  • List Interface 1
  • Maven 1
  • Method Overloading 1
  • Method Overriding 1
  • MySql 2
  • Nested Class 3
  • Object 1
  • OneToMany Mapping 1
  • OneToOne Mapping 1
  • OOP 1
  • PDF 2
  • POST Request 1
  • Predicate 2
  • PriorityQueue 1
  • Programming 27
  • Python 9
  • Queue Interface 1
  • Recursion 6
  • Regular Inner Class 1
  • Rest Api 5
  • Scanner 1
  • Servlet 1
  • Set Interface 1
  • Sliding Window 1
  • SortedSet 1
  • sorting 3
  • Spring 2
  • Spring Boot 5
  • Spring Security 1
  • Stack 1
  • Static Keyword 1
  • String 5
  • Super Keyword 1
  • Supplier 1
  • Text File 2
  • ThymeLeaf 1
  • Time Conversion 1
  • TreeSet 1
  • Two Pointer 2
  • Upload File 1
  • Var-args 3
  • Vector 1

Archive

  • April 2022 4
  • March 2022 5
  • February 2022 4
  • January 2022 2
  • December 2021 5
  • November 2021 5
  • October 2021 5
  • September 2021 7
  • August 2021 7
  • July 2021 8
  • June 2021 6
  • May 2021 10
  • April 2021 6
  • March 2021 8
  • February 2021 2
  • January 2021 10
  • December 2020 6
  • November 2020 4
  • October 2020 5
  • September 2020 3
  • August 2020 2
  • July 2020 3
  • June 2020 5
  • May 2020 3

Источник

Читайте также:  Prime number finding in java
Оцените статью