爪哇 - 多维数组或多维的ArrayLists的ArrayList的数组列表? [英] Java - arraylist of multidimensional arrays or arraylist of multidimensional arraylists?
问题描述
我学习Java和我试图环绕这些数据结构我的头。我在Python / PHP的未来,所以我用动态大小动态数组,并能够多种类型的数据存储在一个数组中。
I'm learning Java and am trying to wrap my head around these data structures. I'm coming from Python/PHP so I'm used to dynamically sizing arrays on the fly and being able to store multiple data types in one array.
如何将我最好的存储这些数据?说我不知道我有多少行会有,但我知道每一行将于2数据列。一列是一个字符串,而另一列属双层。
How would I best store this data? Say I don't know how many rows I'll have, but I do know that each row will hold 2 columns of data. One column being a string, and the other column being a double.
例伪上下的code,如果我有3行:
Example in pseudo-ish code if I had 3 rows:
array(array("description1", 10.00),
array("description2", 12.00),
array("description3", 14.00));
然后,我想遍历数组处理datawith是这样的:
Then, I want to loop through the array to process the datawith something like:
foreach(rows as row){
myStringVal = row[0]; //on first iteration would be "description1"
myIntVal = row[1]; //on first iteration would be 10.00
... do something with the values ...
}
我想我需要创建一个保存了数组一个ArrayList,但我不能存储在一个Java数组字符串和双打,所以我该怎么办?难道我使用地图来代替,并把它当作好像它是一个数组?例如,做我创建了一个地图,第一个元素是各行的数字ID,第二个元素是字符串值,第三个元素是双重价值,然后我用一个循环,增加一个计数器,并抓住每行从用数字标识的地图>
I'm thinking I need to create an arraylist that holds an array, but I can't store both strings and doubles in a java array, so what do i do? Do I use a map instead, and treat it as if it were an array? For example, do I create a map where the first element is a numeric ID for each row, the second element is the string value, the 3rd element is the double value, and then I use a loop to increase a counter and grab each row from the map that using the numeric ID>
真的困惑,这将如何工作。有什么建议么?谢谢!
Really confused as to how this will work. Any suggestions? Thanks!
推荐答案
您不是存储别样的价值观,你存储的语义数据连接codeS一个元组,但使用非的只是粘附在阵列的java概念。不这样做,而是使用编码链接数据的C / C ++ / Java的概念,作为一个结构/对象:
You're not storing "different kind of values", you're storing semantic data that encodes "a tuple" but using the non-java concept of just sticking that in an array. Don't do that, instead use the C/C++/Java concept of encoding linked data as a struct/object:
// our "struct"esque class for the linked data we're handling
class MyObject {
String description;
float value;
Public MyObject(String description, float value) {
this.description = description;
this.value = value;
}
}
// build our list of objects
ArrayList<MyObject> mylist = new ArrayList<MyObject>();
mylist.add(new MyObject("description1", 10));
mylist.add(new MyObject("description2", 12));
mylist.add(new MyObject("description3", 14));
...
// and then we iterate
String d; float v;
for(MyObject m: mylist) {
d = m.description;
v = m.value;
...
}
这篇关于爪哇 - 多维数组或多维的ArrayLists的ArrayList的数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!