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?
My advice is generally you shouldn’t use arrays. You should use
Lists instead. At that point, the choice is made for you. You have to useIntegernotintbecause Java generics don’t support primitive types (unlike, say, C#).Since you’re new to Java, this may introduce a few new concepts to you.
Java Collections don’t have the same limitations as arrays. For example, you don’t have to declare the size of an
ArrayListwhen you create it. Array allocation is abstracted away by this particular class.Now all this assumes you don’t want the result array to be the same size as the input array. There are valid reasons for this (eg when doing vector/matrix maths). The two ways of handling this kind of thing are to use
Integer(so you can putnullfor empty values but this then requires you to test fornull) or by using a sentinel value (egInteger.MAX_VALUE).