[英]How to store a 2D array in a regular array? Java
基本上我希望能夠存儲這樣的2D數組
int [][] preferredMoves = {
{0,0}, {0, arrLength}, {length%2, arrLength},
{0, length%2}, {arrLength, 0}, {0, length%2},
{arrLength, arrLength}, {length%2, length%2},
{arrLength, length%2}, {length%2, 0}
};
在一個
int [] moves;
陣列。
我肯定這是可能的,因為我只是存儲一個列表...,但是我似乎無法在任何地方找到有關此的信息...或者也許不可能?
編輯我正在處理矩陣。 我想將列表存儲在單個數組中,然后返回該數組以在其他地方使用它。
所以每次我叫它時,我要做的就是這樣...
int row = Computer.moves()[0];
int col = Computer.moves()[1];
我還需要遍歷單個數組,該數組多次包含2D數組。
不知道這是否是您的意思,但是您可以刪除內部的{ ... }
來將其轉換為一維數組:
int [] moves = {
0, 0, 0, arrLength, length % 2, arrLength,
0, length % 2, arrLength, 0, 0, length % 2,
arrLength, arrLength, length % 2, length % 2,
arrLength, length % 2, length % 2, 0
};
您可以使用以下公式將2D索引(i, j)
為1D索引k
:
k = i * 2 + j;
Janos的答案可能是您想要的。 或者,您可以創建一個類,例如Pair
,並將其存儲在Pair[]
數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.