How to handle array element between int and Integer

Posted by masato-san on Stack Overflow See other posts from Stack Overflow or by masato-san
Published on 2010-06-17T03:39:30Z Indexed on 2010/06/17 3:43 UTC
Read the original article Hit count: 223

Filed under:
|
|

First, it is long post so if you need clarification please let me know.

I'm new to Java and having difficulty deciding whether I should use int[] or Integer[]. I wrote a function that find odd_number from int[] array.

public int[] find_odd(int[] arr) {
        int[] result = new int[arr.length];
        for(int i=0; i<arr.length; i++) {
            if(arr[i] % 2 != 0) {
                //System.out.println(arr[i]);
                result[i] = arr[i];
            }
        }
        return result;
    }

Then, when I pass the int[] array consisting of some integer like below:

int[] myArray = {-1, 0, 1, 2, 3};
int[] result = find_odd(myArray);

The array "result" contains:

0, -1, 0, 1, 0, 3

Because in Java you have to define the size of array first, and empty int[] array element is 0 not null. So when I want to test the find_odd() function and expect the array to have odd numbers (which it does) only, it throws the error because the array also includes 0s representing "empty cell" as shown above.

My test code:

public void testFindOddPassValidIntArray() {
        int[] arr = {-2, -1, 0, 1, 3};
        int[] result = findOddObj.find_odd(arr);

        //check if return array only contain odd number
        for(int i=0; i<result.length; i++) {
            if(result[i] != null) {
                assert is_odd(result[i]) : result[i];
            }

        }
    }

So, my question is should I use int[] array and add check for 0 element in my test like:

if(result[i] != 0) {
  assert is_odd(result[i] : result[i]
}

But in this case, if find_odd() function is broken and returning 0 by miscalculation, I can't catch it because my test code would only assume that 0 is empty cell.

OR should I use Integer[] array whose default is null? How do people deal with this kind of situation?

© Stack Overflow or respective owner

Related posts about java

Related posts about beginner