Java : List of arrays

Collections_Interface

For creating a list of arrays of int or String, we use an ArrayList.
ArrayList is a class that implements the List interface.

  • To create a list of String array ( String [ ] ) we do the below
    List<String[]> list_str_arrays = new ArrayList<String[]>();
  • To create a list of int array ( int [ ] ) we do the below
    List<int[]> list_str_arrays = new ArrayList<int[]>();

For adding arrays to the list of arrays, we use the addAll function of the Collection interface.

Function
addAll ( Collection C , elements …)
Adds all elements listed to the specified collection.


Java ( Java 11 ) : Below is an example of creating a List of int arrays and a List of String arrays

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

class ListOfArrays {

    public void Display_String_Arrays (List<String[]> list_str_arrays) {

        System.out.println("========= Contents of string arrays ===========");

        int cnt = 0;
        for (String[] arr : list_str_arrays) {
            System.out.println("Array : " + cnt++);
            for (String str : arr) {
                System.out.print("[" + str + "] ");
            } System.out.println();
        }
    }

    public void Display_Int_Arrays (List<int[]> list_int_arrays) {

        System.out.println("\n========= Contents of int arrays ===========");

        int cnt = 0;
        for (int [] arr : list_int_arrays) {
            System.out.println("Array : " + cnt++);
            for (int num : arr) {
                System.out.print(num + " ");
            } System.out.println();
        }
    }

    public static void main (String[] args) {

        String[] _true = { "true", "glumy", "rainbow king", "carlson" };
        String[] _noddy = { "noddy", "deltoid", "pad pad" };
        String[] _glitter_force = { "breeze", "shine", "rain" };

        List<String[]> list_str_arrays = new ArrayList<String[]>();
        Collections.addAll(list_str_arrays, _true, _noddy, _glitter_force);

        ListOfArrays loa = new ListOfArrays();
        loa.Display_String_Arrays(list_str_arrays);

        int[] _prime = { 2, 3, 5, 7 };
        int[] _negative = { -4, -1, -7, -9 };
        int[] _positive = { 5, 22, 32, 41, 79 };

        List<int[]> list_int_arrays = new ArrayList<int[]>();
        Collections.addAll(list_int_arrays, _prime, _negative, _positive);

        loa.Display_Int_Arrays(list_int_arrays);
    }
}

Output

========= Contents of string array ===========
Array : 0
[true] [glumy rainbow] [king carlson]
Array : 1
[noddy] [deltoid] [pad pad]
Array : 2
[breeze] [shine] [rain]

========= Contents of int array ===========
Array : 0
2 3 5 7
Array : 1
-4 -1 -7 -9
Array : 2
5 22 32 41 79


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.