首页 > 解决方案 > 如何在不出现 NullPointException 的情况下将数组的大小加倍?

问题描述

首先,为了快速了解一下,这是我昨天的帖子:

如何解决 Java 中的 NullPointerException?

所以我得到了这个 NullPointerException,我现在相信它发生在我尝试在字符串数组中找到第一个副本的索引之前。在搜索第一个副本的索引之前,我使用此方法将字符串数组的大小加倍:

static String[] upSizeArr( String[] fullArr )
{

    int size = fullArr.length; 
    String[] newSizeArr = new String[(2 * size)]; 
    for (int a = 0; a < size; a++) {
        newSizeArr[a] = fullArr[a];
    }
    return newSizeArr;
}

然后我在这个 while 循环的上下文中使用该方法:

static final int CAPACITY = 10;
int wordCount = 0;

BufferedReader wordFile = new BufferedReader( new FileReader(args[1]) );
String[] wordList = new String[CAPACITY];

while ( wordFile.ready() ) 
    {   if ( wordCount == wordList.length ) 
            wordList = upSizeArr( wordList );
        wordList[wordCount++] = wordFile.readLine();
    } 
wordFile.close();

使用 upSizeArr 方法是否有任何可能的解决方法?我希望解决方案是基本的,并且只使用没有其他数据结构的数组。我是编程新手,我真的很想掌握基础知识……大约一周左右一直在寻找解决这个 NullPointException 的方法。

这是完整的代码:

import java.io.*;
import java.util.*;
public class Practice
{
    static final int CAPACITY = 10;
    static final int NOT_FOUND = -1;
    public static void main (String[] args) throws Exception
    {
        if (args.length < 1 )
        {
            System.out.println("\nusage: C:\\> java Practice <words filename>\n\n"); // i.e. C:\> java Lab2 10Kints.txt 172822words.txt
            System.exit(0);
        }


    String[] wordList = new String[CAPACITY];
    int wordCount = 0;
    BufferedReader wordFile = new BufferedReader( new FileReader(args[0]) );

    while ( wordFile.ready() ) // i.e. while there is another line (word) in the file
    {   if ( wordCount == wordList.length ) 
            wordList = upSizeArr( wordList );
        wordList[wordCount++] = wordFile.readLine();
    } //END WHILE wordFile
    wordFile.close(); 
    System.out.format( "%s loaded into word array. size=%d, count=%d\n",args[0],wordList.length,wordCount );
    int dupeIndex = indexOfFirstDupe( wordList, wordCount );
    if ( dupeIndex == NOT_FOUND )
        System.out.format("No duplicate values found in wordList\n");
    else
        System.out.format("First duplicate value in wordList found at index %d\n",dupeIndex);

} // END OF MAIN

// TWO METHODS 

static String[] upSizeArr( String[] fullArr )
{

    int size = fullArr.length; //find the length of the arrays
    String[] newSizeArr = new String[(2 * size)]; // creates new array, doubled in size
    for (int a = 0; a < size; a++) {
        newSizeArr[a] = fullArr[a];
    }
    return newSizeArr;

}
static int indexOfFirstDupe( String[] arr, int count )
{       
    Arrays.sort(arr);
    int size = arr.length;
    int index = NOT_FOUND;

    for (int x = 0; x < size; x++) {
        for (int y = x + 1; y < size; y++) {
            if (arr[x].equals(arr[y])) {
                index = x;
                break;
            }
        }
    }
    return index;
    }
} // END OF PROGRAM

此外,用作参数的文件是字符串的 txt 文件。

标签: javaarraysnullpointerexception

解决方案


我不确定这是否是你的问题的原因,但它非常可疑......

while ( wordFile.ready() ) {
    //...
}

不是你应该如何阅读文件。相反,您应该检查 的返回结果readLine,它将null在到达文件末尾时返回。

也许更像……

try (BufferedReader wordFile = new BufferedReader(new FileReader(args[1]))) {
    String[] wordList = new String[CAPACITY];

    String text = null;
    while ((text = wordFile.readLine()) != null) {
        if (wordCount == wordList.length) {
            wordList = upSizeArr(wordList);
        }
        wordList[wordCount++] = text;
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

您的代码还会冒着打开文件资源的风险。上面的例子使用了try-with-resources语句来确保它被正确关闭,而不管操作是否成功。

查看try-with-resources 声明以了解更多详细信息。

除非是特定要求,否则我还建议您使用ArrayListSystem.arraycopy过度滚动您自己的解决方案。

也许看看List Implementations了解更多细节

从可运行示例更新...

在没有可运行的代码示例的情况下进行游戏之后,当upSizeArr创建一个新数组时,它会将新元素默认为null,这是预期的,我很惊讶Arrays.sort无法处理这个问题。

“A”解决方案是用不同的非默认值填充未使用的空间......

static String[] upSizeArr(String[] fullArr) {

    int size = fullArr.length; //find the length of the arrays
    String[] newSizeArr = new String[(2 * size)]; // creates new array, doubled in size
    for (int a = 0; a < size; a++) {
        newSizeArr[a] = fullArr[a];
    }
    for (int a = size; a < newSizeArr.length; a++) {
        newSizeArr[a] = "";
    }
    return newSizeArr;

}

“另一种”解决方案可能是“缩小”数组以适应可用数据......

static String[] downsizeToCapacity(String[] fullArr) {
    int lastIndex = 0;
    while (lastIndex < fullArr.length && fullArr[lastIndex] != null) {
        lastIndex++;
    }
    if (lastIndex >= fullArr.length) {
        return fullArr;
    }
    String[] downSized = new String[lastIndex];
    System.arraycopy(fullArr, 0, downSized, 0, lastIndex);

    return downSized;
}

所有这一切都试图做的是创建一个新数组,其大小仅足以包含所有非空值并将其返回。

然后,您可以使用类似...

System.out.format("%s loaded into word array. size=%d, count=%d\n", "words.txt", wordList.length, wordCount);
wordList = downsizeToCapacity(wordList);
System.out.format("%s loaded into word array. size=%d, count=%d\n", "words.txt", wordList.length, wordCount);

int dupeIndex = indexOfFirstDupe(wordList, wordCount);

在我的测试中,输出

words.txt loaded into word array. size=160, count=99
words.txt loaded into word array. size=99, count=99
No duplicate values found in wordList

推荐阅读