How to create a matrix using ArrayList and List in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

public class Program {
    public static void PrintMatrix(List<List<Integer>> matrix) {
        for (List<Integer> list1d : matrix) {
            for (int val : list1d) {
                System.out.print(val + "  ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> matrix = new ArrayList<>();
         
        matrix.add(new ArrayList<>(List.of(1, 2, 3, 1, 4)));
        matrix.add(new ArrayList<>(List.of(2, 7, 8, 3, 3)));
        matrix.add(new ArrayList<>(List.of(3, 6, 9, 1, 5)));
        matrix.add(new ArrayList<>(List.of(1, 2, 3, 4, 8)));

        PrintMatrix(matrix);
    }
}
 
 
 
/*
run:
 
1  2  3  1  4  
2  7  8  3  3  
3  6  9  1  5  
1  2  3  4  8  
 
*/

 



answered Mar 2, 2024 by avibootz

Related questions

2 answers 309 views
1 answer 213 views
213 views asked Jan 16, 2022 by avibootz
1 answer 142 views
2 answers 175 views
3 answers 240 views
240 views asked Mar 22, 2021 by avibootz
1 answer 161 views
161 views asked Jun 28, 2020 by avibootz
...