How to check if array element is null to avoid NullPointerException in Java

后端 未结 9 1045
情深已故
情深已故 2020-12-16 13:08

I have a partially nfilled array of objects, and when I iterate through them I tried to check to see whether the selected object is null before I do other stuff

相关标签:
9条回答
  • 2020-12-16 13:35

    The given code works for me. Notice that someArray[i] is always null since you have not initialized the second dimension of the array.

    0 讨论(0)
  • 2020-12-16 13:35
    public static void main(String s[])
    {
        int firstArray[] = {2, 14, 6, 82, 22};
        int secondArray[] = {3, 16, 12, 14, 48, 96};
        int number = getCommonMinimumNumber(firstArray, secondArray);
        System.out.println("The number is " + number);
    
    }
    public static int getCommonMinimumNumber(int firstSeries[], int secondSeries[])
    {
        Integer result =0;
        if ( firstSeries.length !=0 && secondSeries.length !=0 )
        {
            series(firstSeries);
            series(secondSeries);
            one : for (int i = 0 ; i < firstSeries.length; i++)
            {
                for (int j = 0; j < secondSeries.length; j++)
                    if ( firstSeries[i] ==secondSeries[j])
                    {
                        result =firstSeries[i];
                        break one;
                    }
                    else
                        result = -999;
            }
        }
        else if ( firstSeries == Null || secondSeries == null)
            result =-999;
    
        else
            result = -999;
    
        return result;
    }
    
    public static int[] series(int number[])
    {
    
        int temp;
        boolean fixed = false;
        while(fixed == false)
        {
            fixed = true;
            for ( int i =0 ; i < number.length-1; i++)
            {
                if ( number[i] > number[i+1])
                {
                    temp = number[i+1];
                    number[i+1] = number[i];
                    number[i] = temp;
                    fixed = false;
                }
            }
        }
        /*for ( int i =0 ;i< number.length;i++)
        System.out.print(number[i]+",");*/
        return number;
    
    }
    
    0 讨论(0)
  • 2020-12-16 13:37

    Well, first of all that code doesn't compile.

    After removing the extra semicolon after i++, it compiles and runs fine for me.

    0 讨论(0)
提交回复
热议问题