How to define a two-dimensional array using Vector in Java?

In Java, you can use Vector to define a two-dimensional array. Here is an example code:

import java.util.Vector;

public class Main {
    public static void main(String[] args) {
        // 定义一个Vector对象
        Vector<Vector<Integer>> matrix = new Vector<>();

        // 定义二维数组的行数和列数
        int rows = 3;
        int cols = 4;

        // 初始化二维数组
        for (int i = 0; i < rows; i++) {
            Vector<Integer> row = new Vector<>();
            for (int j = 0; j < cols; j++) {
                // 添加元素到行向量
                row.add(i * cols + j);
            }
            // 添加行向量到矩阵向量
            matrix.add(row);
        }

        // 打印二维数组
        for (Vector<Integer> row : matrix) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}

Executing the above code will produce the following output:

0 1 2 3 
4 5 6 7 
8 9 10 11 

In the code above, we used a Vector object to represent a two-dimensional array. When initializing the two-dimensional array, we created a row vector and added it to the matrix vector. We can then use nested loops to access and manipulate the two-dimensional array.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds