Skip to content

Commit 761304a

Browse files
committed
[array-nullorempty] check array null or empty
1 parent bb4a527 commit 761304a

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung.array.nullorempty;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import java.math.BigDecimal;
7+
8+
import org.apache.commons.lang3.ArrayUtils;
9+
import org.junit.jupiter.api.Test;
10+
11+
public class CheckArrayNullOrEmptyUnitTest {
12+
13+
private final static String[] STR_ARRAY = new String[] { "a", "b", "c", "d" };
14+
private final static BigDecimal[] EMPTY_ARRAY = new BigDecimal[] {};
15+
private final static String[] NULL_ARRAY = null;
16+
// primitive array
17+
private final static int[] INT_ARRAY = new int[] { 1, 2, 3, 4 };
18+
19+
public static <T> boolean isArrayNullOrEmpty(T[] theArray) {
20+
return theArray == null || theArray.length == 0;
21+
}
22+
23+
public static boolean isArrayNullOrEmpty2(Object[] theArray) {
24+
return theArray == null || theArray.length == 0;
25+
}
26+
27+
public static boolean isArrayNullOrEmpty(int[] theArray) {
28+
return theArray == null || theArray.length == 0;
29+
}
30+
31+
@Test
32+
void whenUsingIsArrayNullOrEmpty_thenCorrect() {
33+
assertTrue(isArrayNullOrEmpty(NULL_ARRAY));
34+
assertTrue(isArrayNullOrEmpty(EMPTY_ARRAY));
35+
assertFalse(isArrayNullOrEmpty(STR_ARRAY));
36+
37+
//int array uses isArrayNullOrEmpty(int[] theArray)
38+
assertFalse(isArrayNullOrEmpty(INT_ARRAY));
39+
}
40+
41+
@Test
42+
void whenUsingIsArrayNullOrEmpty2_thenCorrect() {
43+
assertTrue(isArrayNullOrEmpty2(NULL_ARRAY));
44+
assertTrue(isArrayNullOrEmpty2(EMPTY_ARRAY));
45+
assertFalse(isArrayNullOrEmpty2(STR_ARRAY));
46+
47+
//primitive array won't work:
48+
//assertFalse(isArrayNullOrEmpty2(INT_ARRAY));
49+
}
50+
51+
@Test
52+
void whenUsingArrayUtils_thenCorrect() {
53+
assertTrue(ArrayUtils.isEmpty(NULL_ARRAY));
54+
assertTrue(ArrayUtils.isEmpty(EMPTY_ARRAY));
55+
assertFalse(ArrayUtils.isEmpty(STR_ARRAY));
56+
//primitive array
57+
assertFalse(ArrayUtils.isEmpty(INT_ARRAY));
58+
}
59+
}

0 commit comments

Comments
 (0)