You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将ArrayList转换为每行3个元素的二维数组?

Convert ArrayList to 2D Array in Java

Hey there! Let's get your ArrayList converted to a 2D array correctly. First, let's note a couple of issues in your initial code:

  • The 2D array declaration syntax is invalid in Java (String[][] array[n3item][3] isn't the right way; we need to use new String[rows][cols] to initialize it)
  • Java uses 0-based indexing, so your expected array[0][3] would trigger an ArrayIndexOutOfBoundsException—a 3-column array only has indices 0, 1, 2. I'll adjust the implementation to match valid Java behavior while keeping your 3-elements-per-row grouping logic.

Here's the corrected, working implementation:

import java.util.ArrayList;

public class ArrayListTo2DArray {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("A");
        arrayList.add("B");
        arrayList.add("C");
        arrayList.add("D");
        arrayList.add("E");
        arrayList.add("F");

        int totalItems = arrayList.size();
        int itemsPerRow = 3;
        // Calculate total rows: add an extra row if there are leftover elements
        int totalRows = totalItems % itemsPerRow == 0 ? totalItems / itemsPerRow : (totalItems / itemsPerRow) + 1;
        
        // Initialize the 2D array
        String[][] twoDArray = new String[totalRows][itemsPerRow];

        // Populate the 2D array from the ArrayList
        for (int i = 0; i < totalItems; i++) {
            int rowIndex = i / itemsPerRow;
            int colIndex = i % itemsPerRow;
            twoDArray[rowIndex][colIndex] = arrayList.get(i);
        }

        // Verify the result
        for (int row = 0; row < totalRows; row++) {
            for (int col = 0; col < itemsPerRow; col++) {
                System.out.printf("twoDArray[%d][%d] = \"%s\"%n", row, col, twoDArray[row][col]);
            }
        }
    }
}

Key Details:

  • Proper Array Initialization: We calculate the number of rows dynamically—if the total elements aren't a perfect multiple of 3, we add an extra row to hold the remaining items (this works even if you add more elements later).
  • Clean Mapping Logic: Using integer division (i / itemsPerRow) gives the correct row index, while modulo (i % itemsPerRow) gives the column index. This is a straightforward way to translate the linear ArrayList indices into 2D array coordinates.
  • Valid Index Output: The result will match your intended grouping with standard Java indexing:
    • twoDArray[0][0] = "A", twoDArray[0][1] = "B", twoDArray[0][2] = "C"
    • twoDArray[1][0] = "D", twoDArray[1][1] = "E", twoDArray[1][2] = "F"

If you really need to mimic 1-based indexing (like your original array[0][1] idea), note that Java doesn't support this natively—you'd have to make the array columns 4 instead of 3 and ignore index 0, but that's inefficient and not idiomatic. The above approach follows standard Java best practices.

内容的提问来源于stack exchange,提问作者Thanh Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:50:16