001/* 002 * Licensed under the Apache License, Version 2.0 (the "License"); 003 * you may not use this file except in compliance with the License. 004 * You may obtain a copy of the License at 005 * 006 * http://www.apache.org/licenses/LICENSE-2.0 007 * 008 * Unless required by applicable law or agreed to in writing, software 009 * distributed under the License is distributed on an "AS IS" BASIS, 010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 011 * See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014package org.gbif.utils.collection; 015 016import java.lang.reflect.Array; 017 018public class ArrayUtils { 019 020 public static <T> T[] arrayMerge(T[]... arrays) { 021 // Determine required size of new array 022 int count = 0; 023 for (T[] array : arrays) { 024 count += array.length; 025 } 026 027 // create new array of required class 028 T[] mergedArray = (T[]) Array.newInstance(arrays[0][0].getClass(), count); 029 030 // Merge each array into new array 031 int start = 0; 032 for (T[] array : arrays) { 033 System.arraycopy(array, 0, mergedArray, start, array.length); 034 start += array.length; 035 } 036 return mergedArray; 037 } 038 039 public static byte[] arrayMerge(byte[]... arrays) { 040 // Determine required size of new array 041 int count = 0; 042 for (byte[] array : arrays) { 043 count += array.length; 044 } 045 046 // create new array of required class 047 byte[] mergedArray = new byte[count]; 048 049 // Merge each array into new array 050 int start = 0; 051 for (byte[] array : arrays) { 052 System.arraycopy(array, 0, mergedArray, start, array.length); 053 start += array.length; 054 } 055 return mergedArray; 056 } 057 058 public static byte[] intToByteArray(int value) { 059 byte[] b = new byte[4]; 060 for (int i = 0; i < 4; i++) { 061 int offset = (b.length - 1 - i) * 8; 062 b[i] = (byte) ((value >>> offset) & 0xFF); 063 } 064 return b; 065 } 066 067 public static int byteArrayToInt(byte[] b) { 068 return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF); 069 } 070 071 private ArrayUtils() { 072 throw new UnsupportedOperationException("Can't initialize class"); 073 } 074}