001package org.gbif.utils.collection;
002
003import java.lang.reflect.Array;
004
005public class ArrayUtils {
006
007  public static <T> T[] arrayMerge(T[]... arrays) {
008    // Determine required size of new array
009    int count = 0;
010    for (T[] array : arrays) {
011      count += array.length;
012    }
013
014    // create new array of required class
015    T[] mergedArray = (T[]) Array.newInstance(arrays[0][0].getClass(), count);
016
017    // Merge each array into new array
018    int start = 0;
019    for (T[] array : arrays) {
020      System.arraycopy(array, 0, mergedArray, start, array.length);
021      start += array.length;
022    }
023    return mergedArray;
024  }
025
026  public static byte[] arrayMerge(byte[]... arrays) {
027    // Determine required size of new array
028    int count = 0;
029    for (byte[] array : arrays) {
030      count += array.length;
031    }
032
033    // create new array of required class
034    byte[] mergedArray = new byte[count];
035
036    // Merge each array into new array
037    int start = 0;
038    for (byte[] array : arrays) {
039      System.arraycopy(array, 0, mergedArray, start, array.length);
040      start += array.length;
041    }
042    return mergedArray;
043  }
044
045  public static byte[] intToByteArray(int value) {
046    byte[] b = new byte[4];
047    for (int i = 0; i < 4; i++) {
048      int offset = (b.length - 1 - i) * 8;
049      b[i] = (byte) ((value >>> offset) & 0xFF);
050    }
051    return b;
052  }
053
054  public static int byteArrayToInt(byte[] b) {
055    return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF);
056  }
057
058  private ArrayUtils() {
059    throw new UnsupportedOperationException("Can't initialize class");
060  }
061}