我们如何可以动态分配和成长的数组 [英] How can we dynamically allocate and grow an array
问题描述
我工作的一个项目,但我不能使用任何现有的Java数据结构(即ArraysList,树木等)
I am working on a project, but I cannot use any existing java data structures (ie, ArraysList, trees, etc)
我只能用数组。因此,我需要一个动态更新与新的内存中的数组。
I can only use arrays. Therefore, I need to dynamically update an array with new memory.
我从一个文本文件中读取,并为内存数组我pre-100分配:
I am reading from a text file, and I pre-allocate 100 for the arrays memory:
String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null) {
// Store the content into an array
Scanner s = new Scanner(strLine);
while(s.hasNext()) {
wordList[wordCount] = s.next();
wordCount++;
}
}
现在这工作正常下100列表项。 br.readline是缓冲的读者通过文本文件的每一行去。我有那么每个单词存储到列表中,然后递增我的索引(的wordCount)。
Now this works fine for under 100 list items. br.readline is the buffered reader going through each line of a textfile. I have it then store each word into list and then increment my index (wordCount).
但是,一旦我有超过100个项目的文本文件,我得到一个分配错误。
However, once I have a text file with more than 100 items, I get an allocation error.
我怎样才能动态地更新这个数组(从而排序推倒重来)?
How can I dynamically update this array (and thereby sort of reinvent the wheel)?
谢谢!
推荐答案
您可以做这样的事情:
String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null) {
// Store the content into an array
Scanner s = new Scanner(strLine);
while(s.hasNext()) {
if (wordList.length == wordCount) {
// expand list
wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
}
wordList[wordCount] = s.next();
wordCount++;
}
}
使用 java.util.Arrays.copyOf(字符串[])
基本上是做同样的事情:
Using java.util.Arrays.copyOf(String[])
is basically doing the same thing as:
if (wordList.length == wordCount) {
String[] temp = new String[wordList.length + arrayGrowth];
System.arraycopy(wordList, 0, temp, 0, wordList.length);
wordList = temp;
}
除了它是code,而不是三一行。 :)
except it is one line of code instead of three. :)
这篇关于我们如何可以动态分配和成长的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!