我們如何一起使用Arrays和ArrayLists(如果可能的話)?ArrayLists和Arrays如何在Java中相互交互?
我想儲存一些字符串到一個ArrayList,後來拉出來,它們解析成字符串數組,這些數組存儲在一個ArrayList,並能夠檢索以後的ArrayList中的數據...
看看這段代碼,隨時帶我分開做蹩腳的編碼;自從我使用Java以來已經有一段時間了。
public static void parseData() throws IOException
{
//for reference, nonParsedData is ArrayList<String>
// while parsedData is ArrayList<String[]>
String line = new String();
String[] tempContainer = new String[7];
Scanner keyboard = new Scanner(System.in);
for (int x = 0; x < nonParsedData.size(); x++)
{
line = nonParsedData.get(x);
//filling the temporary container to place into the ArrayList of arrays
tempContainer[0] = line.substring(0,1); //Data piece 1
tempContainer[1] = line.substring(1,3); //Data piece 2
tempContainer[2] = line.substring(3,7); //Data piece 3
tempContainer[3] = line.substring(7,8); //Data piece 4
tempContainer[4] = line.substring(8,9); //Data piece 5
tempContainer[5] = line.substring(9,10); //Data piece 6
tempContainer[6] = line.substring(10,(line.length() - 1)); //Data piece 7
parsedData.add(tempContainer);
}
}
所以在前面,我已經傾倒了一些外部文件到nonParsedData
。這是一串字符串。沒什麼大不了。我把這些字符串,讀取它們,把它們放入數組中。 Hunky dory。這工作正常。
這是檢索過程,這使我中風。三次 -
public static void fetchAndPrint() throws IOException
{
String[] tempContainer = new String[7];
for(int x = 0; x < parsedData.size(); x++)
{
tempContainer = parsedData.get(x); //this should be assigning my stored array to
//the tempContainer array (I think)
//let's try deepToString (that didn't work)
//System.out.println((parsedData.get(x)).toString()); //just a debugging check
System.out.println(x);
System.out.println(tempContainer[0] + " " + tempContainer[1] + " "
+ tempContainer[2] + " " + tempContainer[3] + " "
+ tempContainer[4] + " " + tempContainer[5] + " "
+ tempContainer[6] + " ");
}
}
我這樣做之後,只有我一個輸出從最初ArrayList<String[]>
顯示出來!我在循環中錯過了什麼嗎?當我真的沒有這個功能時,我是否正在實施ArrayList
的陣列?我不正確地給數組賦值? ArrayList
甚至會給我一個實際的數組 - 或者它只是一個像{1,2,3等}的列表?這些事情甚至不同嗎?
最後,我知道這可以使用數據庫語言來實現,但我們假設我想堅持使用Java。
http://stackoverflow.com/questions/9929321/converting-arraylist-to-array-in-java – EMM 2014-10-29 15:58:32
上述帖子不是我所需要的,但謝謝。使用字符串從ArrayList中創建數組沒有問題,它是一旦存儲的數組將檢索到有問題的數組。 – 2014-10-29 16:43:57