Last active
December 15, 2015 03:39
-
-
Save ThomasOwens/5196178 to your computer and use it in GitHub Desktop.
Utility methods for working with Arrays.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
/** | |
* A collection of utilities for working with arrays. | |
* | |
* @author Thomas Owens | |
*/ | |
public class ArrayUtils { | |
/** | |
* Concatenate all of the specified arrays into one array. | |
* | |
* @param first | |
* the first array to concatenate | |
* @param rest | |
* the following arrays to concatenate | |
* @throws IllegalArgumentException | |
* an argument is null or the concatenation is too large for an | |
* array | |
* @return array that represents the concatenation of all of the arrays in | |
* the order they were passed | |
*/ | |
public static <T> T[] concatAll(T[] first, T[]... rest) { | |
if (first == null) { | |
throw new IllegalArgumentException("Array can not be null."); | |
} | |
long totalLength = first.length; | |
for (T[] array : rest) { | |
if (array == null) { | |
continue; | |
} | |
totalLength += array.length; | |
} | |
if (totalLength < 0 || totalLength > Integer.MAX_VALUE) { | |
throw new IllegalArgumentException("Invalid array size."); | |
} | |
T[] result = Arrays.copyOf(first, (int) totalLength); | |
int offset = first.length; | |
for (T[] array : rest) { | |
if (array == null) { | |
continue; | |
} | |
System.arraycopy(array, 0, result, offset, array.length); | |
offset += array.length; | |
} | |
return result; | |
} | |
/** | |
* Determine if the array contains the specified pattern. | |
* | |
* @param array | |
* the array to search | |
* @param pattern | |
* the pattern to search for | |
* @throws IllegalArgumentException | |
* if either array is null or if the pattern is larger than the | |
* array | |
* @return true if the array contains the specified pattern, false otherwise | |
*/ | |
public static boolean arrayContains(byte[] array, byte[] pattern) { | |
if (array == null || pattern == null) { | |
throw new IllegalArgumentException("Arrays must be non-null"); | |
} | |
if (pattern.length > array.length) { | |
throw new IllegalArgumentException( | |
"Pattern must be equal to or greater than the containing array."); | |
} | |
if (pattern.length == 0) { | |
return true; | |
} | |
outer: for (int i = 0; i < array.length - pattern.length + 1; i++) { | |
for (int j = 0; j < pattern.length; j++) { | |
if (array[i + j] != pattern[j]) { | |
continue outer; | |
} | |
} | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment