为什么我会收到带有字符串数组的 NullPointerException?

Why am I getting a NullPointerException with an array of Strings?

我制作了一个函数,可以按字母顺序对随机生成的字符串数组进行排序。在我的代码的第 64 行,我总是得到一个 NullPointerException,即使我写了 if 语句来检查数组在某些索引处是否有空值。我还在创建随机数组的 main() 中确保 String[] 数组的索引不应该为空。那么问题是什么?这是代码:

/**
    This program takes an array of random integers or strings and sorts them with selection sort and Arrays.sort() and determines which method of sorting is faster.
*/

import java.util.Arrays;

public class SortAssess{

    /**
        This function takes an unsorted integer array and sorts it using the selection sort method.
        Precondition: An array of int values.
        Postcondition: A sorted array of int values.

        @param baseArr This is the array that is to be sorted.
        @return The sorted baseArr.
    */
    static int[] selectionSort(int[] baseArr){

        int lastPlace;
        int maxPos;

        for(lastPlace = baseArr.length - 1; lastPlace > 0; lastPlace--){//Decreases part of the array to be iterated by one each search cycle.

            maxPos = 0;//Index of the largest element in the subarray.

            for(int i = 1; i <= lastPlace; i++){

                if(baseArr[maxPos] < baseArr[i])
                    maxPos = i;

            }

            int temp = baseArr[lastPlace];
            baseArr[lastPlace] = baseArr[maxPos];
            baseArr[maxPos] = temp;

        }

        return baseArr;

    }

    /**
        This function takes an unsorted String array and sorts it using the selection sort method.
        Precondition: An array of String values.
        Postcondition: A sorted array of String values.

        @param baseArr This is the array that is to be sorted.
        @return The sorted baseArr.
    */
    static String[] selectionSort(String[] baseArr){

        int lastPlace;
        int maxPos;

        for(lastPlace = baseArr.length - 1; lastPlace > 0; lastPlace--){//Decreases part of the array to be iterated by one each search cycle.

            maxPos = 0;//Index of the largest element in the subarray.

            for(int i = 1; i <= lastPlace; i++){

                int j = 0;

                while(baseArr[i].charAt(j) == baseArr[maxPos].charAt(j)){//NullPointerException
                    j++;
                }

                if(baseArr[maxPos].charAt(j) < baseArr[i].charAt(j))
                    maxPos = i;

            }

            String temp = baseArr[lastPlace];
            baseArr[lastPlace] = baseArr[maxPos];
            baseArr[maxPos] = temp;

        }

        return baseArr;

    }

    public static void main(String[] args){

        int[] randInts = new int[10000];
        String[] randStrings = new String[10000];
        String randString;//A single string to be added to randStrings, with random characters and length.
        long start, end, elapsed;//start of timer, end, and difference.

        //assign random values to randInts
        for(int i = 0; i < 10000; i++){
            randInts[i] = (int)(Math.random() * 100000);
        }

        //assign random values to randStrings
        for(int i = 0; i < 12; i++){

            randString = "";//initializes the string.

            //Create string at i of random length and with each index a random character
            for(int j = 0; j < ((int)(Math.random() * 40) + 5); j++){//creates a random length.
                randString += String.valueOf((char)((int)(Math.random() * 26) + 65));//generates ASCII code for character, which is converted to char and added 
                //to string.
            }

            randStrings[i] = randString;
            System.out.println(randString);

        }

        start = System.currentTimeMillis();
        selectionSort(randInts);
        end = System.currentTimeMillis();
        elapsed = end - start;
        System.out.println("Selection sort of random integers took " + elapsed + " milliseconds.");

        start = System.currentTimeMillis();
        Arrays.sort(randInts);
        end = System.currentTimeMillis();
        elapsed = end - start;
        System.out.println("Built-in sort of random integers took " + elapsed + " milliseconds.");

        start = System.currentTimeMillis();
        selectionSort(randStrings);
        end = System.currentTimeMillis();
        elapsed = end - start;
        System.out.println("Selection sort of random strings took " + elapsed + " milliseconds.");

        start = System.currentTimeMillis();
        Arrays.sort(randStrings);
        end = System.currentTimeMillis();
        elapsed = end - start;
        System.out.println("Built-in sort of random strings took " + elapsed + " milliseconds.");

    }

}

您只初始化了其中的十二个。

//assign random values to randStrings
for(int i = 0; i < 12; i++) {
     // loop to deal with string array
}

在处理数组时,您应该考虑使用 randStrings.length;这样一来,如果你心血来潮改变数组的长度,就不会再出现这个问题了。

//assign random values to randStrings
for(int i = 0; i < randStrings.length; i++) {
     // loop to deal with string array
}

那里也要小心;我确实注意到 selectionSort 内的 while 循环中有一个 StringIndexOutOfBoundsException。仔细检查您是否正在根据边界进行迭代。

除了@Makoto 提供的答案之外,您还声明了 randStrings 来存储 1000 个字符串,但您只分配了 12 个字符串。其余的显然指向 null,因此 NullPointerException

一个建议

每当您发现自己遇到此类问题时,请输入 println 语句以更好地了解您遇到的情况 exception。用这种方法问题就解决了一半。