Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array is empty? [closed]

Tags:

java

arrays

I have written a program where if the array set is let's say {1, 3, 6, 7, 12}, it will return its minimum gap between two numbers. In other words, it will first find the differences between 3 and 1, 6 and 3, 7 and 6, and 12 and 7. After their differences are achieved, it will return the least difference, in our case 1, since 6-7=1. If we were given an array set of {60}, for example, the program will return 0. Now if we had an array set of {}, where nothing is inside, it will return 0 as well. However, I can't get my program to return a 0! It throws an exception. What did I miss? How should I solve this problem? Here is my program so far:

public static void main(String[] args) {
    int[] numberSet = {1, 3, 6, 7, 12};
    //int[] numberSet = {};
    System.out.println(minGap(numberSet));      
}

public static int minGap(int[] numberSet) {
    int[] differenceArray = new int[numberSet.length-1];
    int smallestNum = 0;
    if (numberSet.length < 2) {
        return 0;
    }
    else {
        for(int i = 0; i < numberSet.length-1; i++) {
            differenceArray[i] = numberSet[i+1] - numberSet[i]; 
        }       
        Arrays.sort(differenceArray);
        smallestNum = differenceArray[0];
        return smallestNum;
    }
}

Thanks in advance!

like image 669
user1029481 Avatar asked Feb 10 '13 06:02

user1029481


2 Answers

To check array is null:

int arr[] = null;
if (arr == null) {
 System.out.println("array is null");
}

To check array is empty:

arr = new int[0];
if (arr.length == 0) {
 System.out.println("array is empty");
}
like image 65
Achintya Jha Avatar answered Sep 17 '22 21:09

Achintya Jha


Your test:

if (numberSet.length < 2) {
    return 0;
}

should be done before you allocate an array of that length in the below statement:

int[] differenceArray = new int[numberSet.length-1];

else you are already creating an array of size -1, when the numberSet.length = 0. That is quite odd. So, move your if statement as the first statement in your method.

like image 39
Rohit Jain Avatar answered Sep 20 '22 21:09

Rohit Jain