[英]Store a 2D array into an array?
所以我在这里有这个方法。 这是创建一个2D数组。
public static int[][] createCacheArray(int cacheSize, int blockSize, int[] memory, int i) {
//Create multi-dimension array for cache.
int [][] cache = new int [cacheSize/blockSize][blockSize];
for (int column = 0; column < blockSize; column++) {
for (int row = 0; row < cache.length; row++) {
cache[row][column] = memory[i];
i++;
}
}
return cache;
}
我想将创建的Cache 2D数组存储到一维数组中,因为我将使用相同的方法制作多个2D缓存数组,我想组织它们。
基本上我想去一个Cache二维数组所在的数组[数字],然后读取该缓存二维数组的内容。 如果有另一种方法,我会很乐意欣赏它。
另一种方法是:
cache = createCacheArray(cacheSize, blockSize, memory, (cacheSize * 0)); cache1 = createCacheArray(cacheSize, blockSize, memory, (cacheSize * 1)); cache2 = createCacheArray(cacheSize, blockSize, memory, (cacheSize * 2)); cache3 = createCacheArray(cacheSize, blockSize, memory, (cacheSize * 3));
这里,缓存是2D阵列,cache1是2D阵列,缓存2是2D阵列等等,但这是不方便的。 我问的原因是因为这些是固定的64x16 2D阵列。 如果数组被填充,那么我必须制作另一个具有相同大小的2D数组。 而不是制作多个变量,我认为有可能以某种方式将这些变量存储到数组中。 就像二维阵列一样,书籍和一维阵列就是书架。
==================
2D阵列内部有数字。
在做了AndersonVieira的建议之后,我的所有2D数组都存储在ArrayList中。 太棒了。
我现在要做的就是在ArrayList中的所有2D数组中搜索特定数字。 但我不知道要写什么代码来做这件事。 我还是Java的初学者。
您可以创建一个List<int[][]>
并将缓存存储在那里:
List<int[][]> caches = new ArrayList<>();
for (int i = 0; i < numCaches; i++) {
caches.add(createCacheArray(cacheSize, blockSize, memory, (cacheSize * i)));
}
然后,您可以通过执行以下操作来访问缓存:
int[][] cache = caches.get(j);
其中j
是caches
列表中所需元素的索引。
或者,如果您需要对每个存储的缓存执行某些操作,则可以迭代列表:
for (int[][] cache : caches) {
doSomething(cache);
}
与使用3D阵列相比,这可能更容易使用。
编辑:
要检查二维数组是否包含元素,您需要循环遍历将位置值与所需值进行比较的所有位置:
static boolean contains(int element, int[][] cache) {
for (int i = 0; i < cache.length; i++) {
for (j = 0; j < cache[i].length; j++) {
if (cache[i][j] == element) {
return true;
}
}
}
return false;
}
然后,您可以创建一个返回包含指定元素的第一个缓存的方法,否则返回null
:
static int[][] cacheContaining(int element, List<int[][]> caches) {
for (int[][] cache : caches) {
if (contains(element, cache)) {
return cache;
}
}
return null;
}
你可以使用像3d一样的数组,
int[][][] cache = {
createCacheArray(cacheSize, blockSize, memory, (cacheSize * 0)),
createCacheArray(cacheSize, blockSize, memory, (cacheSize * 1)),
createCacheArray(cacheSize, blockSize, memory, (cacheSize * 2)),
createCacheArray(cacheSize, blockSize, memory, (cacheSize * 3))
};
System.out.println(Arrays.deepToString(cache);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.