[英]How to create Dynamic Two Dimensional Array [JAVA]
I am new to java and I want to create a 2-dimensional array in which the rows are static but the columns are dynamic. 我是java新手,我想创建一个二维数组,其中行是静态的,但列是动态的。
double [][] lastSecArray = new double [2][41];
int lastValue = -1;
public foo (){
lastValue++;
lastSecArray[0][lastValue] = st_ms;
//more code here
}
The value of lastValue increases and when it reaches 41 my program gives me Array Index out of bound. lastValue的值增加,当它达到41时,我的程序给出了数组索引超出范围。 Which is what I should expect.
这是我应该期待的。
How can I make the column of teh array dynamic so that no matter how large the value of lastValue increases it runs. 如何使teh数组的列动态化,以便无论lastValue的值增加多大,它都会运行。
It may be more appropriate to use a Map<Double, List<Double>>
. 使用
Map<Double, List<Double>>
可能更合适。 Having the value of the Map
as a List<Double>
will allow you to expand the list as opposed to an array which has a fixed size. 将
Map
的值作为List<Double>
将允许您展开列表而不是具有固定大小的数组。
public static void main(String[] args) throws CloneNotSupportedException {
Map<Double, List<Double>> myMap = create(1, 3);
}
public static Map<Double, List<Double>> create(double row, double column) {
Map<Double, List<Double>> doubleMap = new HashMap<Double, List<Double>>();
for (double x = 0; x < row; x++) {
for (double y = 0; y < column; y++) {
doubleMap.put(x, new ArrayList<Double>());
}
}
return doubleMap;
}
Try to use 尝试使用
Map<String, ArrayList> lastSecArray = new HashMap<>();
ArrayList value = new ArrayList();
value.add(0);
value.add(1);
value.add(2);
lastSecArray.put("0", value);
so you can operate with 所以你可以操作
lastSecArray.size()
or 要么
lastSecArray.put(...)
or array in array 或数组中的数组
I assume you're coming from the C-world. 我假设你来自C世界。 In Java, you have many objects which represent arrays.
在Java中,您有许多表示数组的对象。
I suggest you to check this link : ArrayList . 我建议你查看这个链接: ArrayList 。 This is a class which uses a resizable array.
这是一个使用可调整大小的数组的类。
I think this is a good way to have a dynamic two dimensionnal Array in Java. 我认为这是在Java中使用动态二维数组的好方法。
As ArrayList is a template class, you are able to create ArrayList<ArrayList<double>>
, or if you want to have a "static" number of rows, you can create ArrayList<double[2]>
. 由于ArrayList是模板类,因此您可以创建
ArrayList<ArrayList<double>>
,或者如果您希望具有“静态”行数,则可以创建ArrayList<double[2]>
。
in Java arrays are fixed size so what you are saying is not possoble. 在Java数组中是固定大小的,所以你所说的不是可以。
take a look at this thread might help you. 看看这个帖子可能对你有帮助。
If you know the element size at runtime 如果您知道运行时的元素大小
int size=runtime decides;
double [][] lastSecArray = new double [2][size];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.