我们如何动态分配和增长数组 [英] How can we dynamically allocate and grow an array

查看:39
本文介绍了我们如何动态分配和增长数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目,但我不能使用任何现有的 java 数据结构(即 ArraysList、trees 等)

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.

我正在读取一个文本文件,并为数组内存预分配了 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(String[]) 基本上做同样的事情:

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;
}

除了它是一行代码而不是三行.:)

except it is one line of code instead of three. :)

这篇关于我们如何动态分配和增长数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆