0
# Array Utilities
1
2
Apache Commons Lang provides extensive array manipulation capabilities through ArrayUtils and related classes. The ArrayUtils class alone offers 368 static methods, making it a comprehensive toolkit for array operations that Java's standard library lacks.
3
4
## Core Classes
5
6
### ArrayUtils - Comprehensive Array Operations
7
8
The primary array utility class with 368 static methods supporting all primitive types and object arrays:
9
10
```java { .api }
11
import org.apache.commons.lang3.ArrayUtils;
12
```
13
14
#### Constants and Empty Arrays
15
16
```java { .api }
17
// Empty array constants for all types
18
public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]
19
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]
20
public static final char[] EMPTY_CHAR_ARRAY = new char[0]
21
public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]
22
public static final float[] EMPTY_FLOAT_ARRAY = new float[0]
23
public static final int[] EMPTY_INT_ARRAY = new int[0]
24
public static final long[] EMPTY_LONG_ARRAY = new long[0]
25
public static final short[] EMPTY_SHORT_ARRAY = new short[0]
26
public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]
27
public static final String[] EMPTY_STRING_ARRAY = new String[0]
28
29
// Index not found constant
30
public static final int INDEX_NOT_FOUND = -1
31
```
32
33
**Usage Examples:**
34
```java { .api }
35
// Using empty array constants instead of creating new arrays
36
String[] emptyStrings = ArrayUtils.EMPTY_STRING_ARRAY;
37
int[] emptyInts = ArrayUtils.EMPTY_INT_ARRAY;
38
39
// Safe array initialization
40
String[] array = condition ? actualArray : ArrayUtils.EMPTY_STRING_ARRAY;
41
```
42
43
#### Array Creation and Basic Operations
44
45
```java { .api }
46
// Array length and null safety
47
public static int getLength(Object array)
48
public static boolean isEmpty(Object[] array)
49
public static boolean isNotEmpty(Object[] array)
50
51
// Array copying and cloning
52
public static <T> T[] clone(T[] array)
53
public static <T> T[] nullToEmpty(T[] array, Class<T[]> type)
54
```
55
56
**Usage Examples:**
57
```java { .api }
58
// Null-safe operations
59
int length = ArrayUtils.getLength(null); // 0
60
boolean empty = ArrayUtils.isEmpty(new String[0]); // true
61
boolean notEmpty = ArrayUtils.isNotEmpty(new String[]{"a"}); // true
62
63
// Safe array handling
64
String[] array = null;
65
String[] safe = ArrayUtils.nullToEmpty(array, String[].class); // Returns empty array
66
67
// Array cloning
68
String[] original = {"a", "b", "c"};
69
String[] copy = ArrayUtils.clone(original);
70
```
71
72
#### Adding Elements
73
74
```java { .api }
75
// Adding single elements (returns new array)
76
public static boolean[] add(boolean[] array, boolean element)
77
public static byte[] add(byte[] array, byte element)
78
public static char[] add(char[] array, char element)
79
public static double[] add(double[] array, double element)
80
public static float[] add(float[] array, float element)
81
public static int[] add(int[] array, int element)
82
public static long[] add(long[] array, long element)
83
public static short[] add(short[] array, short element)
84
public static <T> T[] add(T[] array, T element)
85
86
// Adding at specific index
87
public static <T> T[] add(T[] array, int index, T element)
88
89
// Adding multiple elements
90
public static <T> T[] addAll(T[] array1, T... array2)
91
```
92
93
**Usage Examples:**
94
```java { .api }
95
// Adding single elements
96
int[] numbers = {1, 2, 3};
97
int[] moreNumbers = ArrayUtils.add(numbers, 4); // [1, 2, 3, 4]
98
99
// Adding at specific position
100
String[] words = {"hello", "world"};
101
String[] inserted = ArrayUtils.add(words, 1, "beautiful"); // ["hello", "beautiful", "world"]
102
103
// Adding multiple elements
104
int[] first = {1, 2};
105
int[] second = {3, 4};
106
int[] combined = ArrayUtils.addAll(first, second); // [1, 2, 3, 4]
107
108
// Handling null arrays safely
109
int[] nullArray = null;
110
int[] withElement = ArrayUtils.add(nullArray, 1); // [1]
111
```
112
113
#### Removing Elements
114
115
```java { .api }
116
// Removing elements by index
117
public static boolean[] remove(boolean[] array, int index)
118
public static <T> T[] remove(T[] array, int index)
119
120
// Removing elements by value
121
public static boolean[] removeElement(boolean[] array, boolean element)
122
public static <T> T[] removeElement(T[] array, Object element)
123
124
// Removing multiple elements
125
public static <T> T[] removeElements(T[] array, T... values)
126
public static <T> T[] removeAll(T[] array, int... indices)
127
128
// Removing all occurrences
129
public static <T> T[] removeAllOccurences(T[] array, T element)
130
```
131
132
**Usage Examples:**
133
```java { .api }
134
// Removing by index
135
String[] words = {"apple", "banana", "cherry"};
136
String[] removed = ArrayUtils.remove(words, 1); // ["apple", "cherry"]
137
138
// Removing by value
139
int[] numbers = {1, 2, 3, 2, 4};
140
int[] withoutTwo = ArrayUtils.removeElement(numbers, 2); // [1, 3, 2, 4] (removes first occurrence)
141
142
// Removing multiple elements
143
String[] fruits = {"apple", "banana", "cherry", "date"};
144
String[] fewer = ArrayUtils.removeElements(fruits, "banana", "date"); // ["apple", "cherry"]
145
146
// Removing all occurrences
147
int[] repeated = {1, 2, 2, 3, 2, 4};
148
int[] cleaned = ArrayUtils.removeAllOccurences(repeated, 2); // [1, 3, 4]
149
```
150
151
#### Array Searching
152
153
```java { .api }
154
// Basic search operations
155
public static int indexOf(Object[] array, Object objectToFind)
156
public static int indexOf(Object[] array, Object objectToFind, int startIndex)
157
public static int lastIndexOf(Object[] array, Object objectToFind)
158
159
// Contains operations
160
public static boolean contains(Object[] array, Object objectToFind)
161
162
// For primitive arrays (example with int)
163
public static int indexOf(int[] array, int valueToFind)
164
public static boolean contains(int[] array, int valueToFind)
165
```
166
167
**Usage Examples:**
168
```java { .api }
169
// Searching in arrays
170
String[] fruits = {"apple", "banana", "cherry", "banana"};
171
int firstBanana = ArrayUtils.indexOf(fruits, "banana"); // 1
172
int lastBanana = ArrayUtils.lastIndexOf(fruits, "banana"); // 3
173
boolean hasApple = ArrayUtils.contains(fruits, "apple"); // true
174
175
// Searching with start index
176
int nextBanana = ArrayUtils.indexOf(fruits, "banana", 2); // 3
177
178
// Primitive array search
179
int[] numbers = {10, 20, 30, 20, 40};
180
boolean hasThirty = ArrayUtils.contains(numbers, 30); // true
181
int firstTwenty = ArrayUtils.indexOf(numbers, 20); // 1
182
```
183
184
#### Array Manipulation
185
186
```java { .api }
187
// Reversing arrays (in-place modification)
188
public static void reverse(Object[] array)
189
public static void reverse(Object[] array, int startIndexInclusive, int endIndexExclusive)
190
191
// Shuffling arrays
192
public static void shuffle(Object[] array)
193
public static void shuffle(Object[] array, Random random)
194
195
// Swapping elements
196
public static void swap(Object[] array, int offset1, int offset2)
197
public static void swap(Object[] array, int offset1, int offset2, int len)
198
```
199
200
**Usage Examples:**
201
```java { .api }
202
// Array reversal
203
String[] words = {"first", "second", "third"};
204
ArrayUtils.reverse(words); // ["third", "second", "first"]
205
206
// Partial reversal
207
int[] numbers = {1, 2, 3, 4, 5};
208
ArrayUtils.reverse(numbers, 1, 4); // [1, 4, 3, 2, 5]
209
210
// Array shuffling
211
String[] deck = {"A", "B", "C", "D"};
212
ArrayUtils.shuffle(deck); // Random order
213
214
// Element swapping
215
String[] items = {"a", "b", "c", "d"};
216
ArrayUtils.swap(items, 0, 2); // ["c", "b", "a", "d"]
217
```
218
219
#### Array Comparison and Equality
220
221
```java { .api }
222
// Array comparison
223
public static boolean isEquals(Object array1, Object array2)
224
public static boolean isSameLength(Object[] array1, Object[] array2)
225
public static boolean isSameType(Object array1, Object array2)
226
227
// Sorted array operations
228
public static boolean isSorted(Comparable[] array)
229
public static <T> boolean isSorted(T[] array, Comparator<T> comparator)
230
```
231
232
**Usage Examples:**
233
```java { .api }
234
// Array comparison
235
String[] array1 = {"a", "b", "c"};
236
String[] array2 = {"a", "b", "c"};
237
boolean equal = ArrayUtils.isEquals(array1, array2); // true
238
239
// Length comparison
240
boolean sameLength = ArrayUtils.isSameLength(array1, array2); // true
241
242
// Sort checking
243
Integer[] sorted = {1, 2, 3, 4, 5};
244
Integer[] unsorted = {3, 1, 4, 2, 5};
245
boolean isSorted1 = ArrayUtils.isSorted(sorted); // true
246
boolean isSorted2 = ArrayUtils.isSorted(unsorted); // false
247
```
248
249
#### Subarray Operations
250
251
```java { .api }
252
// Creating subarrays
253
public static <T> T[] subarray(T[] array, int startIndexInclusive, int endIndexExclusive)
254
255
// Array splitting
256
public static <T> T[][] split(T[] array, int... indices)
257
```
258
259
**Usage Examples:**
260
```java { .api }
261
// Subarray extraction
262
String[] words = {"apple", "banana", "cherry", "date", "elderberry"};
263
String[] middle = ArrayUtils.subarray(words, 1, 4); // ["banana", "cherry", "date"]
264
265
// Array splitting
266
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
267
int[][] parts = ArrayUtils.split(numbers, 2, 5); // [[1,2], [3,4,5], [6,7,8]]
268
```
269
270
#### Type Conversion
271
272
```java { .api }
273
// Primitive to Object array conversion
274
public static Boolean[] toObject(boolean[] array)
275
public static Byte[] toObject(byte[] array)
276
public static Character[] toObject(char[] array)
277
public static Double[] toObject(double[] array)
278
public static Float[] toObject(float[] array)
279
public static Integer[] toObject(int[] array)
280
public static Long[] toObject(long[] array)
281
public static Short[] toObject(short[] array)
282
283
// Object to primitive array conversion
284
public static boolean[] toPrimitive(Boolean[] array)
285
public static boolean[] toPrimitive(Boolean[] array, boolean valueForNull)
286
// ... similar for other types
287
```
288
289
**Usage Examples:**
290
```java { .api }
291
// Converting primitives to objects
292
int[] primitives = {1, 2, 3, 4, 5};
293
Integer[] objects = ArrayUtils.toObject(primitives); // [1, 2, 3, 4, 5]
294
295
// Converting objects to primitives
296
Integer[] integers = {10, 20, null, 30};
297
int[] converted = ArrayUtils.toPrimitive(integers, 0); // [10, 20, 0, 30] (null becomes 0)
298
299
// Safe conversion with null handling
300
Boolean[] booleans = {true, false, null};
301
boolean[] bools = ArrayUtils.toPrimitive(booleans, false); // [true, false, false]
302
```
303
304
### ArraySorter - Array Sorting Utilities
305
306
Provides convenient sorting methods for arrays:
307
308
```java { .api }
309
import org.apache.commons.lang3.ArraySorter;
310
```
311
312
#### Sorting Operations
313
314
```java { .api }
315
// Sorting primitive arrays (returns new sorted array)
316
public static byte[] sort(byte[] array)
317
public static char[] sort(char[] array)
318
public static double[] sort(double[] array)
319
public static float[] sort(float[] array)
320
public static int[] sort(int[] array)
321
public static long[] sort(long[] array)
322
public static short[] sort(short[] array)
323
324
// Sorting object arrays
325
public static <T> T[] sort(T[] array)
326
public static <T> T[] sort(T[] array, Comparator<? super T> comparator)
327
```
328
329
**Usage Examples:**
330
```java { .api }
331
// Sorting primitive arrays
332
int[] unsorted = {3, 1, 4, 1, 5, 9, 2, 6};
333
int[] sorted = ArraySorter.sort(unsorted); // [1, 1, 2, 3, 4, 5, 6, 9]
334
335
// Sorting objects with custom comparator
336
String[] words = {"banana", "apple", "cherry"};
337
String[] sortedWords = ArraySorter.sort(words, String.CASE_INSENSITIVE_ORDER);
338
339
// Note: Original arrays remain unchanged
340
System.out.println(Arrays.equals(unsorted, sorted)); // false
341
```
342
343
### ArrayFill - Array Initialization Utilities
344
345
Provides methods for filling arrays with values:
346
347
```java { .api }
348
import org.apache.commons.lang3.ArrayFill;
349
```
350
351
#### Filling Operations
352
353
```java { .api }
354
// Fill arrays with specific values
355
public static boolean[] fill(boolean[] a, boolean val)
356
public static byte[] fill(byte[] a, byte val)
357
public static char[] fill(char[] a, char val)
358
public static double[] fill(double[] a, double val)
359
public static float[] fill(float[] a, float val)
360
public static int[] fill(int[] a, int val)
361
public static long[] fill(long[] a, long val)
362
public static short[] fill(short[] a, short val)
363
public static <T> T[] fill(T[] a, T val)
364
365
// Fill with function-generated values
366
public static <T, E extends Throwable> T[] fill(T[] array, FailableIntFunction<? extends T, E> generator) throws E
367
```
368
369
**Usage Examples:**
370
```java { .api }
371
// Filling arrays with values
372
int[] zeros = new int[5];
373
ArrayFill.fill(zeros, 0); // [0, 0, 0, 0, 0]
374
375
String[] defaults = new String[3];
376
ArrayFill.fill(defaults, "default"); // ["default", "default", "default"]
377
378
// Filling with generated values
379
Integer[] squares = new Integer[5];
380
ArrayFill.fill(squares, i -> i * i); // [0, 1, 4, 9, 16]
381
```
382
383
## Advanced Array Operations
384
385
### Multi-dimensional Array Support
386
387
```java { .api }
388
// Working with multi-dimensional arrays
389
Object[][] matrix = {{"a", "b"}, {"c", "d"}};
390
int length = ArrayUtils.getLength(matrix); // 2
391
boolean empty = ArrayUtils.isEmpty(matrix[0]); // false
392
393
// Converting jagged arrays
394
String[][] jagged = {{"1", "2"}, {"3"}};
395
String[] flattened = Arrays.stream(jagged)
396
.flatMap(Arrays::stream)
397
.toArray(String[]::new); // ["1", "2", "3"]
398
```
399
400
### Performance Considerations
401
402
```java { .api }
403
// Efficient array operations
404
public class ArrayProcessor {
405
406
// Pre-allocate arrays when size is known
407
public String[] processItems(List<String> items) {
408
String[] result = new String[items.size()];
409
for (int i = 0; i < items.size(); i++) {
410
result[i] = processItem(items.get(i));
411
}
412
return result;
413
}
414
415
// Use ArrayUtils for safe operations
416
public boolean[] combineFlags(boolean[] flags1, boolean[] flags2) {
417
if (ArrayUtils.isEmpty(flags1)) return ArrayUtils.clone(flags2);
418
if (ArrayUtils.isEmpty(flags2)) return ArrayUtils.clone(flags1);
419
420
return ArrayUtils.addAll(flags1, flags2);
421
}
422
423
// Batch operations for better performance
424
public int[] removeMultipleElements(int[] array, int... indicesToRemove) {
425
// Sort indices in descending order to avoid index shifting issues
426
int[] sortedIndices = Arrays.stream(indicesToRemove)
427
.boxed()
428
.sorted(Collections.reverseOrder())
429
.mapToInt(Integer::intValue)
430
.toArray();
431
432
int[] result = array;
433
for (int index : sortedIndices) {
434
result = ArrayUtils.remove(result, index);
435
}
436
return result;
437
}
438
}
439
```
440
441
## Common Usage Patterns
442
443
### Safe Array Processing
444
445
```java { .api }
446
public class SafeArrayProcessor {
447
448
public static <T> List<T> arrayToList(T[] array) {
449
if (ArrayUtils.isEmpty(array)) {
450
return Collections.emptyList();
451
}
452
return Arrays.asList(array);
453
}
454
455
public static String[] filterNonNull(String[] array) {
456
if (ArrayUtils.isEmpty(array)) {
457
return ArrayUtils.EMPTY_STRING_ARRAY;
458
}
459
460
return Arrays.stream(array)
461
.filter(Objects::nonNull)
462
.toArray(String[]::new);
463
}
464
465
public static <T> T getElementAt(T[] array, int index, T defaultValue) {
466
if (ArrayUtils.isEmpty(array) || index < 0 || index >= array.length) {
467
return defaultValue;
468
}
469
return array[index];
470
}
471
}
472
```
473
474
### Array Building Patterns
475
476
```java { .api }
477
public class ArrayBuilder<T> {
478
private List<T> elements = new ArrayList<>();
479
private final Class<T> type;
480
481
public ArrayBuilder(Class<T> type) {
482
this.type = type;
483
}
484
485
public ArrayBuilder<T> add(T element) {
486
if (element != null) {
487
elements.add(element);
488
}
489
return this;
490
}
491
492
public ArrayBuilder<T> addAll(T... elements) {
493
if (ArrayUtils.isNotEmpty(elements)) {
494
Collections.addAll(this.elements, elements);
495
}
496
return this;
497
}
498
499
@SuppressWarnings("unchecked")
500
public T[] build() {
501
return elements.toArray((T[]) Array.newInstance(type, elements.size()));
502
}
503
}
504
505
// Usage example
506
String[] result = new ArrayBuilder<>(String.class)
507
.add("first")
508
.addAll("second", "third")
509
.add(null) // Ignored
510
.build(); // ["first", "second", "third"]
511
```
512
513
### Integration with Streams
514
515
```java { .api }
516
public class ArrayStreamIntegration {
517
518
// Convert array to stream safely
519
public static <T> Stream<T> stream(T[] array) {
520
return ArrayUtils.isEmpty(array) ?
521
Stream.empty() :
522
Arrays.stream(array);
523
}
524
525
// Filter and collect to array
526
public static String[] filterAndSort(String[] input) {
527
return stream(input)
528
.filter(StringUtils::isNotBlank)
529
.sorted()
530
.toArray(String[]::new);
531
}
532
533
// Group array elements
534
public static Map<Boolean, List<Integer>> partitionNumbers(int[] numbers) {
535
return ArrayUtils.isEmpty(numbers) ?
536
Collections.emptyMap() :
537
Arrays.stream(ArrayUtils.toObject(numbers))
538
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
539
}
540
}
541
```
542
543
## Thread Safety and Immutability
544
545
All ArrayUtils methods are thread-safe as they operate on immutable inputs and return new arrays rather than modifying existing ones:
546
547
```java { .api }
548
public class ThreadSafeArrayOperations {
549
550
private static final String[] IMMUTABLE_CONSTANTS = {"READ", "WRITE", "EXECUTE"};
551
552
// Thread-safe array operations
553
public String[] getPermissionsFor(User user) {
554
String[] basePermissions = ArrayUtils.clone(IMMUTABLE_CONSTANTS);
555
556
if (user.isAdmin()) {
557
return ArrayUtils.add(basePermissions, "ADMIN");
558
}
559
560
return basePermissions;
561
}
562
563
// Concurrent array processing
564
public int[] processConcurrently(int[] input) {
565
return Arrays.stream(ArrayUtils.nullToEmpty(input, int[].class))
566
.parallel()
567
.map(this::expensiveOperation)
568
.toArray();
569
}
570
}
571
```
572
573
The array utilities in Apache Commons Lang provide comprehensive, null-safe, and efficient operations for all array manipulation needs, filling significant gaps in Java's standard library while maintaining excellent performance characteristics.