Java/Collections Data Structure/Array Convert — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 10:27, 1 июня 2010

Array Converter

   <source lang="java">
 

/**

* 
* LibFormula : a free Java formula library
* 
*
* Project Info:  http://reporting.pentaho.org/libformula/
*
* (C) Copyright 2006-2007, by Pentaho Corporation and Contributors.
*
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
*
* ------------
* $Id: ArrayConverter.java 3521 2007-10-16 10:55:14Z tmorgner $
* ------------
* (C) Copyright 2006-2007, by Pentaho Corporation.
*/

import java.util.ArrayList; import java.util.List; import java.lang.reflect.Array; /**

* Creation-Date: 08.10.2006, 17:37:50
*
* @author Thomas Morgner
*/

public class ArrayConverter {

 private ArrayConverter()
 {
 }
 public static Object[] getAsList(final Object maybeArray,
                                  final Class arrayType)
 {
   if (maybeArray == null)
   {
     return null;
   }
   if (maybeArray.getClass().isArray() == false)
   {
     return new Object[]{maybeArray};
   }
   final ArrayList list = new ArrayList();
   ArrayConverter.addToList(list, maybeArray);
   final Object o = Array.newInstance(arrayType, list.size());
   return list.toArray((Object[]) o);
 }
 private static void addToList (final List list, final Object array)
 {
   final int length = Array.getLength(array);
   for (int i = 0; i < length; i++)
   {
     final Object value = Array.get(array, i);
     if (value == null)
     {
       list.add(null);
       continue;
     }
     if (value.getClass().isArray() == false)
     {
       list.add(value);
       continue;
     }
     ArrayConverter.addToList(list, value);
   }
 }
 /**
  * @param maybeArray
  * @param dimensions
  * @return
  */
 public static Object[] getArray(final Object maybeArray,
                                 final Class arrayType,
                                 final int dims)
 {
   if (maybeArray == null)
   {
     return null;
   }
   if (dims <= 0)
   {
     return null;
   }
   if (maybeArray.getClass().isArray() == false)
   {
     Object object = maybeArray;
     for (int i = 0; i < dims; i++)
     {
       final Object[] array = (Object[]) Array.newInstance(arrayType, 1);
       array[0] = object;
       object = array;
     }
     return (Object[]) object;
   }
   if (ArrayConverter.getDimensionCount(maybeArray.getClass()) < dims)
   {
     return null;
   }
   return (Object[]) maybeArray;
 }
 public static int getDimensionCount(Class arrayClass)
 {
   int count = 0;
   while (arrayClass != null && arrayClass.isArray())
   {
     count += 1;
     arrayClass = arrayClass.getComponentType();
   }
   return count;
 }

}


 </source>
   
  
 
  



Array helper

   <source lang="java">
 

/*

* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA  02110-1301  USA
*
*/

import java.lang.reflect.Array; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; public final class ArrayHelper {

 public static int indexOf(Object[] array, Object object) {
   for (int i = 0; i < array.length; i++) {
     if (array[i].equals(object))
       return i;
   }
   return -1;
 }
 public static String[] toStringArray(Object[] objects) {
   int length = objects.length;
   String[] result = new String[length];
   for (int i = 0; i < length; i++) {
     result[i] = objects[i].toString();
   }
   return result;
 }
 public static String[] fillArray(String value, int length) {
   String[] result = new String[length];
   Arrays.fill(result, value);
   return result;
 }
 public static int[] fillArray(int value, int length) {
   int[] result = new int[length];
   Arrays.fill(result, value);
   return result;
 }
 public static String[] toStringArray(Collection coll) {
   return (String[]) coll.toArray(EMPTY_STRING_ARRAY);
 }
 public static String[][] to2DStringArray(Collection coll) {
   return (String[][]) coll.toArray(new String[coll.size()][]);
 }
 public static int[][] to2DIntArray(Collection coll) {
   return (int[][]) coll.toArray(new int[coll.size()][]);
 }
 public static Type[] toTypeArray(Collection coll) {
   return (Type[]) coll.toArray(EMPTY_TYPE_ARRAY);
 }
 public static int[] toIntArray(Collection coll) {
   Iterator iter = coll.iterator();
   int[] arr = new int[coll.size()];
   int i = 0;
   while (iter.hasNext()) {
     arr[i++] = ((Integer) iter.next()).intValue();
   }
   return arr;
 }
 public static boolean[] toBooleanArray(Collection coll) {
   Iterator iter = coll.iterator();
   boolean[] arr = new boolean[coll.size()];
   int i = 0;
   while (iter.hasNext()) {
     arr[i++] = ((Boolean) iter.next()).booleanValue();
   }
   return arr;
 }
 public static Object[] typecast(Object[] array, Object[] to) {
   return java.util.Arrays.asList(array).toArray(to);
 }
 // Arrays.asList doesn"t do primitive arrays
 public static List toList(Object array) {
   if (array instanceof Object[])
     return Arrays.asList((Object[]) array); // faster?
   int size = Array.getLength(array);
   ArrayList list = new ArrayList(size);
   for (int i = 0; i < size; i++) {
     list.add(Array.get(array, i));
   }
   return list;
 }
 public static String[] slice(String[] strings, int begin, int length) {
   String[] result = new String[length];
   for (int i = 0; i < length; i++) {
     result[i] = strings[begin + i];
   }
   return result;
 }
 public static Object[] slice(Object[] objects, int begin, int length) {
   Object[] result = new Object[length];
   for (int i = 0; i < length; i++) {
     result[i] = objects[begin + i];
   }
   return result;
 }
 public static List toList(Iterator iter) {
   List list = new ArrayList();
   while (iter.hasNext()) {
     list.add(iter.next());
   }
   return list;
 }
 public static String[] join(String[] x, String[] y) {
   String[] result = new String[x.length + y.length];
   for (int i = 0; i < x.length; i++)
     result[i] = x[i];
   for (int i = 0; i < y.length; i++)
     result[i + x.length] = y[i];
   return result;
 }
 public static String[] join(String[] x, String[] y, boolean[] use) {
   String[] result = new String[x.length + countTrue(use)];
   for (int i = 0; i < x.length; i++)
     result[i] = x[i];
   int k = x.length;
   for (int i = 0; i < y.length; i++) {
     if (use[i])
       result[k++] = y[i];
   }
   return result;
 }
 public static int[] join(int[] x, int[] y) {
   int[] result = new int[x.length + y.length];
   for (int i = 0; i < x.length; i++)
     result[i] = x[i];
   for (int i = 0; i < y.length; i++)
     result[i + x.length] = y[i];
   return result;
 }
 public static final boolean[] TRUE = { true };
 public static final boolean[] FALSE = { false };
 private ArrayHelper() {
 }
 public static String toString(Object[] array) {
   StringBuffer sb = new StringBuffer();
   sb.append("[");
   for (int i = 0; i < array.length; i++) {
     sb.append(array[i]);
     if (i < array.length - 1)
       sb.append(",");
   }
   sb.append("]");
   return sb.toString();
 }
 public static boolean isAllNegative(int[] array) {
   for (int i = 0; i < array.length; i++) {
     if (array[i] >= 0)
       return false;
   }
   return true;
 }
 public static boolean isAllTrue(boolean[] array) {
   for (int i = 0; i < array.length; i++) {
     if (!array[i])
       return false;
   }
   return true;
 }
 public static int countTrue(boolean[] array) {
   int result = 0;
   for (int i = 0; i < array.length; i++) {
     if (array[i])
       result++;
   }
   return result;
 }
 /*
  * public static int countFalse(boolean[] array) { int result=0; for ( int
  * i=0; i<array.length; i++ ) { if ( !array[i] ) result++; } return result; }
  */
 public static boolean isAllFalse(boolean[] array) {
   for (int i = 0; i < array.length; i++) {
     if (array[i])
       return false;
   }
   return true;
 }
 public static void addAll(Collection collection, Object[] array) {
   for (int i = 0; i < array.length; i++) {
     collection.add(array[i]);
   }
 }
 public static final String[] EMPTY_STRING_ARRAY = {};
 public static final int[] EMPTY_INT_ARRAY = {};
 public static final boolean[] EMPTY_BOOLEAN_ARRAY = {};
 public static final Class[] EMPTY_CLASS_ARRAY = {};
 public static final Object[] EMPTY_OBJECT_ARRAY = {};
 public static final Type[] EMPTY_TYPE_ARRAY = {};
 public static int[] getBatchSizes(int maxBatchSize) {
   int batchSize = maxBatchSize;
   int n = 1;
   while (batchSize > 1) {
     batchSize = getNextBatchSize(batchSize);
     n++;
   }
   int[] result = new int[n];
   batchSize = maxBatchSize;
   for (int i = 0; i < n; i++) {
     result[i] = batchSize;
     batchSize = getNextBatchSize(batchSize);
   }
   return result;
 }
 private static int getNextBatchSize(int batchSize) {
   if (batchSize <= 10) {
     return batchSize - 1; // allow 9,8,7,6,5,4,3,2,1
   } else if (batchSize / 2 < 10) {
     return 10;
   } else {
     return batchSize / 2;
   }
 }
 private static int SEED = 23;
 private static int PRIME_NUMER = 37;
 /**
  * calculate the array hash (only the first level)
  */
 public static int hash(Object[] array) {
   int length = array.length;
   int seed = SEED;
   for (int index = 0; index < length; index++) {
     seed = hash(seed, array[index] == null ? 0 : array[index].hashCode());
   }
   return seed;
 }
 /**
  * calculate the array hash (only the first level)
  */
 public static int hash(char[] array) {
   int length = array.length;
   int seed = SEED;
   for (int index = 0; index < length; index++) {
     seed = hash(seed, (int) array[index]);
   }
   return seed;
 }
 /**
  * calculate the array hash (only the first level)
  */
 public static int hash(byte[] bytes) {
   int length = bytes.length;
   int seed = SEED;
   for (int index = 0; index < length; index++) {
     seed = hash(seed, (int) bytes[index]);
   }
   return seed;
 }
 private static int hash(int seed, int i) {
   return PRIME_NUMER * seed + i;
 }
 /**
  * Compare 2 arrays only at the first level
  */
 public static boolean isEquals(Object[] o1, Object[] o2) {
   if (o1 == o2)
     return true;
   if (o1 == null || o2 == null)
     return false;
   int length = o1.length;
   if (length != o2.length)
     return false;
   for (int index = 0; index < length; index++) {
     if (!o1[index].equals(o2[index]))
       return false;
   }
   return true;
 }
 /**
  * Compare 2 arrays only at the first level
  */
 public static boolean isEquals(char[] o1, char[] o2) {
   if (o1 == o2)
     return true;
   if (o1 == null || o2 == null)
     return false;
   int length = o1.length;
   if (length != o2.length)
     return false;
   for (int index = 0; index < length; index++) {
     if (!(o1[index] == o2[index]))
       return false;
   }
   return true;
 }
 /**
  * Compare 2 arrays only at the first level
  */
 public static boolean isEquals(byte[] b1, byte[] b2) {
   if (b1 == b2)
     return true;
   if (b1 == null || b2 == null)
     return false;
   int length = b1.length;
   if (length != b2.length)
     return false;
   for (int index = 0; index < length; index++) {
     if (!(b1[index] == b2[index]))
       return false;
   }
   return true;
 }

}


 </source>
   
  
 
  



byte array to int array

   <source lang="java">
 

/*

* Permission is hereby granted, free of charge, to any person obtaining a copy of 
* this software and associated documentation files (the "Software"), to deal in 
* the Software without restriction, including without limitation the rights to 
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
* SOFTWARE.
*/

public class ArrayCopy {

   public static int[] byte2int(byte[]src) {
       int dstLength = src.length >>> 2;
       int[]dst = new int[dstLength];
       
       for (int i=0; i<dstLength; i++) {
           int j = i << 2;
           int x = 0;
           x += (src[j++] & 0xff) << 0;
           x += (src[j++] & 0xff) << 8;
           x += (src[j++] & 0xff) << 16;
           x += (src[j++] & 0xff) << 24;
           dst[i] = x;
       }
       return dst;
   }

}


 </source>
   
  
 
  



Convert array to string

   <source lang="java">
 

/* ArraysX.java {{IS_NOTE

 Purpose:
 Description:
 History:
   2001/11/13, Henri Chen: Created.

}}IS_NOTE Copyright (C) 2001 Potix Corporation. All Rights Reserved. {{IS_RIGHT

 This program is distributed under GPL Version 3.0 in the hope that
 it will be useful, but WITHOUT ANY WARRANTY.

}}IS_RIGHT

  • /

import java.lang.reflect.Array; /**

* Utilities for handling arrays.
*
* @author henrichen
*/

public class ArraysX {

 /** Converts an array to a readable string (for debugging purpose).
  */
 public final static String toString(Object[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     if (array[j] == array)
       sb.append("(this array)");
     else
       sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of int to a readable string (for debugging purpose).
  */
 public final static String toString(int[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of long to a readable string (for debugging purpose).
  */
 public final static String toString(long[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of short to a readable string (for debugging purpose).
  */
 public final static String toString(short[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of byte to a readable string (for debugging purpose).
  */
 public final static String toString(byte[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of char to a readable string (for debugging purpose).
  */
 public final static String toString(char[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of boolean to a readable string (for debugging purpose).
  */
 public final static String toString(boolean[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of float to a readable string (for debugging purpose).
  */
 public final static String toString(float[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /** Converts an array of char to a readable string (for debugging purpose).
  */
 public final static String toString(double[] array) {
   if (array == null)
     return "null";
   StringBuffer sb = new StringBuffer(128).append("[");
   for (int j = 0; j < array.length; ++j) {
     sb.append(array[j]);
     if (j != array.length - 1)
       sb.append(", ");
   }
   return sb.append("]").toString();
 }
 /**
  * Returns the hex String representation of a byte array without prefix 0x.
  * The String is formed by making value[0] the leftmost two digits and
  * value[value.length-1] the rightmost two digits.
  *
  * @param array the byte array
  */
 public final static String toHexString(byte[] array) {
   StringBuffer sb = new StringBuffer(array.length*2 + 8);
   char ch;
   for (int i=0; i< array.length; i++) {
     // byte will be promote to integer first, mask with 0x0f is a must.
     ch = Character.forDigit(array[i] >>> 4 & 0x0f, 16);
     sb.append(ch);
     ch = Character.forDigit(array[i] & 0x0f, 16);
     sb.append(ch);
   }
   return sb.toString();
 }
 /**
  * Returns the octal String representation of a byte array with optional
  * prefix. The String is formed by making value[0] the leftmost three digits
  * and value[value.length-1] the rightmost three digits.
  *
  * @param array the byte array
  */
 public final static String toOctalString(byte[] array, String prefix) {
   StringBuffer sb = new StringBuffer(array.length*(3+prefix.length()) + 8);
   if (prefix == null) {
     for (int i=0; i< array.length; i++) {
       appendOctalDigits(sb, array[i]);
     }
   } else {
     for (int i=0; i< array.length; i++) {
       sb.append(prefix);
       appendOctalDigits(sb, array[i]);
     }
   }
   return sb.toString();
 }
 /**
  * Returns the octal digit String buffer representation of a byte.
  * @param byte the byte
  */
 private final static StringBuffer appendOctalDigits(StringBuffer sb, byte b) {
   // b will be promote to integer first, mask with 0x07 is a must.
   return sb.append(Character.forDigit(b >>> 6 & 0x07, 8))
     .append(Character.forDigit(b >>> 3 & 0x07, 8))
     .append(Character.forDigit(b & 0x07, 8));
 }
 /**
  * Duplicates the specified array.
  *
*

The array could be an array of objects or primiitives. * * @param ary the array * @param jb the beginning index (included) * @param je the ending index (excluded) * @return an array duplicated from ary * @exception IllegalArgumentException if ary is not any array * @exception IndexOutOfBoundsException if out of bounds */ public static final Object duplicate(Object ary, int jb, int je) { int len = Array.getLength(ary); if (jb<0 || je>len || jb>je) throw new IndexOutOfBoundsException(jb + " or " + je + " exceeds " + len); len = je - jb; Object dst = Array.newInstance(ary.getClass().getComponentType(), len); System.arraycopy(ary, jb, dst, 0, len); return dst; } /** * Duplicates the specified array. * @param ary the array * @return an array duplicated from ary * @exception IllegalArgumentException if ary is not any array * @exception IndexOutOfBoundsException if out of bounds */ public static final Object duplicate(Object ary) { return duplicate(ary, 0, Array.getLength(ary)); } /** * Concat the two specified array. * * <p>The array could be an array of objects or primiitives. * * @param ary the array * @param ary1 the array * @return an array concat the ary and ary1 * @exception IllegalArgumentException if ary and ary1 component type are different */ public static final Object concat(Object ary, Object ary1) { int len = Array.getLength(ary) + Array.getLength(ary1); if (!ary.getClass().getComponentType().equals(ary1.getClass().getComponentType())) throw new IllegalArgumentException("These concated array component type are different."); Object dst = Array.newInstance(ary.getClass().getComponentType(), len); System.arraycopy(ary, 0, dst, 0, Array.getLength(ary)); System.arraycopy(ary1, 0, dst, Array.getLength(ary), Array.getLength(ary1)); return dst; } /** * Shrink the specified array. It is similar to duplicate, except * it returns the previous instance if je==length && jb==0. * * @param ary the array * @param jb the beginning index (included) * @param je the ending index (excluded) * @return ary or an array duplicated from ary * @exception IllegalArgumentException if ary is not any array * @exception IndexOutOfBoundsException if out of bounds */ public static final Object shrink(Object ary, int jb, int je) { if (jb == 0 && je == Array.getLength(ary)) return ary; //nothing changed return duplicate(ary, jb, je); } /** * Resizes the specified array. Similar to {@link #shrink}, but * it can enlarge and it keeps elements from the first. */ public static final Object resize(Object ary, int size) { final int oldsz = Array.getLength(ary); if (oldsz == size) return ary; final Object dst = Array.newInstance(ary.getClass().getComponentType(), size); System.arraycopy(ary, 0, dst, 0, oldsz > size ? size: oldsz); return dst; } /** Clones an array. */ public static final Object clone(Object ary) { final int size = Array.getLength(ary); final Object dst = Array.newInstance(ary.getClass().getComponentType(), size); System.arraycopy(ary, 0, dst, 0, size); return dst; } } </source>

Convert array to string (from c3p0)

   <source lang="java">
 

/**

* Distributed as part of c3p0 v.0.9.1.2
* 
* Copyright (C) 2005 Machinery For Change, Inc.
* 
* Author: Steve Waldman <swaldman@mchange.ru>
* 
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License version 2.1, as published
* by the Free Software Foundation.
* 
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
* 
* You should have received a copy of the GNU Lesser General Public License
* along with this software; see the file LICENSE. If not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
* USA.
*/

public final class ArrayUtils {

 /**
  * The array may contain nulls, but o must be non-null.
  */
 public static int indexOf(Object[] array, Object o) {
   for (int i = 0, len = array.length; i < len; ++i)
     if (o.equals(array[i]))
       return i;
   return -1;
 }
 public static int identityIndexOf(Object[] array, Object o) {
   for (int i = 0, len = array.length; i < len; ++i)
     if (o == array[i])
       return i;
   return -1;
 }
 public static boolean startsWith(byte[] checkMe, byte[] maybePrefix) {
   int cm_len = checkMe.length;
   int mp_len = maybePrefix.length;
   if (cm_len < mp_len)
     return false;
   for (int i = 0; i < mp_len; ++i)
     if (checkMe[i] != maybePrefix[i])
       return false;
   return true;
 }
 /**
  * returns a hash-code for an array consistent with Arrays.equals( ... )
  */
 public static int hashArray(int[] ii) {
   int len = ii.length;
   int out = len;
   for (int i = 0; i < len; ++i) {
     // we rotate the bits of the element hashes
     // around so that the hash has some loaction
     // dependency
     int elem_hash = ii[i];
     int rot = i % 32;
     int rot_hash = elem_hash >>> rot;
     rot_hash |= elem_hash << (32 - rot);
     out ^= rot_hash;
   }
   return out;
 }
 public static int hashOrZeroArray(int[] ii) {
   return (ii == null ? 0 : hashArray(ii));
 }
 // these methods are obsoleted by Arrays.toString() in jdk1.5, but
 // for libs that support older VMs...
 private static String toString(String[] strings, int guessed_len) {
   StringBuffer sb = new StringBuffer(guessed_len);
   boolean first = true;
   sb.append("[");
   for (int i = 0, len = strings.length; i < len; ++i) {
     if (first)
       first = false;
     else
       sb.append(",");
     sb.append(strings[i]);
   }
   sb.append("]");
   return sb.toString();
 }
 public static String toString(boolean[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(byte[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(char[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(short[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(int[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(long[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(float[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(double[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 public static String toString(Object[] arr) {
   String[] strings = new String[arr.length];
   int chars = 0;
   for (int i = 0, len = arr.length; i < len; ++i) {
     String str;
     Object o = arr[i];
     if (o instanceof Object[])
       str = toString((Object[]) o);
     else if (o instanceof double[])
       str = toString((double[]) o);
     else if (o instanceof float[])
       str = toString((float[]) o);
     else if (o instanceof long[])
       str = toString((long[]) o);
     else if (o instanceof int[])
       str = toString((int[]) o);
     else if (o instanceof short[])
       str = toString((short[]) o);
     else if (o instanceof char[])
       str = toString((char[]) o);
     else if (o instanceof byte[])
       str = toString((byte[]) o);
     else if (o instanceof boolean[])
       str = toString((boolean[]) o);
     else
       str = String.valueOf(arr[i]);
     chars += str.length();
     strings[i] = str;
   }
   return toString(strings, chars + arr.length + 1);
 }
 private ArrayUtils() {
 }
 /*
  * public static void main(String[] argv) { int[] is = {1,2,3,4}; String[] ss =
  * {"Hello", "There"}; Object[] os = {"Poop", is, ss, new Thread()};
  * 
  * System.out.println( toString(is) ); System.out.println( toString(ss) );
  * System.out.println( toString(os) ); }
  */

}


 </source>
   
  
 
  



Convert byte array to Integer and Long

   <source lang="java">
 

/*

* Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
*
* Licensed under the Aduna BSD-style license.
*/

public class Utils {

 public static void putInt(int value, byte[] array, int offset) {
   array[offset]   = (byte)(0xff & (value >> 24));
   array[offset+1] = (byte)(0xff & (value >> 16));
   array[offset+2] = (byte)(0xff & (value >> 8));
   array[offset+3] = (byte)(0xff & value);
 }
 public static int getInt(byte[] array, int offset) {
   return
     ((array[offset]   & 0xff) << 24) |
     ((array[offset+1] & 0xff) << 16) |
     ((array[offset+2] & 0xff) << 8) |
      (array[offset+3] & 0xff);
 }
 public static void putLong(long value, byte[] array, int offset) {
   array[offset]   = (byte)(0xff & (value >> 56));
   array[offset+1] = (byte)(0xff & (value >> 48));
   array[offset+2] = (byte)(0xff & (value >> 40));
   array[offset+3] = (byte)(0xff & (value >> 32));
   array[offset+4] = (byte)(0xff & (value >> 24));
   array[offset+5] = (byte)(0xff & (value >> 16));
   array[offset+6] = (byte)(0xff & (value >> 8));
   array[offset+7] = (byte)(0xff & value);
 }
 public static long getLong(byte[] array, int offset) {
   return
     ((long)(array[offset]   & 0xff) << 56) |
     ((long)(array[offset+1] & 0xff) << 48) |
     ((long)(array[offset+2] & 0xff) << 40) |
     ((long)(array[offset+3] & 0xff) << 32) |
     ((long)(array[offset+4] & 0xff) << 24) |
     ((long)(array[offset+5] & 0xff) << 16) |
     ((long)(array[offset+6] & 0xff) << 8) |
     ((long)(array[offset+7] & 0xff));
 }

}


 </source>
   
  
 
  



Convert byte array to string

   <source lang="java">
 

/*

  Copyright (C) 2002 MySQL AB
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    
*/

import java.io.UnsupportedEncodingException;

/**

* Various utility methods for converting to/from byte
* arrays in the platform encoding
* 
* @author Mark Matthews
*/

public class StringUtils {

   //~ Instance/static variables .............................................
   private static final int BYTE_RANGE = (1 + Byte.MAX_VALUE)
                                         - Byte.MIN_VALUE;
   private static byte[] allBytes = new byte[BYTE_RANGE];
   private static char[] byteToChars = new char[BYTE_RANGE];
   //~ Initializers ..........................................................
   static {
       for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
           allBytes[i - Byte.MIN_VALUE] = (byte) i;
       }
       String allBytesString = new String(allBytes, 0, 
                                          Byte.MAX_VALUE - Byte.MIN_VALUE);
       for (int i = 0; i < (Byte.MAX_VALUE - Byte.MIN_VALUE); i++) {
           byteToChars[i] = allBytesString.charAt(i);
       }
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @param startPos DOCUMENT ME!
    * @param length DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString3(byte[] buffer, int startPos, 
                                             int length) {
       char[] charArray = new char[length];
       int readpoint = startPos;
       for (int i = 0; i < length; i++) {
           charArray[i] = byteToChars[(int) buffer[readpoint]
                          - Byte.MIN_VALUE];
           readpoint++;
       }
       return new String(charArray);
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString(byte[] buffer) {
       return toAsciiString3(buffer, 0, buffer.length);
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @param startPos DOCUMENT ME!
    * @param length DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString2(byte[] buffer, int startPos, 
                                             int length) {
       return new String(buffer, startPos, length);
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @param startPos DOCUMENT ME!
    * @param length DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString(byte[] buffer, int startPos, 
                                            int length) {
       StringBuffer result = new StringBuffer();
       int endPoint = startPos + length;
       for (int i = startPos; i < endPoint; i++) {
           result.append(byteToChars[(int) buffer[i] - Byte.MIN_VALUE]);
       }
       return result.toString();
   }

}


 </source>
   
  
 
  



Converts a Array to an Enumeration and allows it to be serialized

   <source lang="java">
 

/*

* Copyright Javelin Software, All rights reserved.
*/

import java.util.*; import java.io.*; /**

* An ArrayEnumeration converts a Array to an Enumeration and allows it
* to be serialized. 
* <p>
* @author Robin Sharp
*/

public class ArrayEnumeration implements Enumeration, Serializable {

   /**
    * Construct a fully qualified ArrayEnumeration.
    * @param array the array to be Enumerated.
    */
    public ArrayEnumeration(Object[] array)
    {
        this.array = array;
    }
    // ENUMERATION /////////////////////////////////////////////////////////
   /**
    * @return true if there are more elements in the enumeration.
    */
   public boolean hasMoreElements()
   {
       return array != null && index < array.length;
   }
   /**
    * @return the next element in the enumeration
    */
   public Object nextElement()
   {
       return array[index++];
   }
   // PRIVATE /////////////////////////////////////////////////////////////
   private Object[] array;
   private int index;

}


 </source>
   
  
 
  



int array to byte array

   <source lang="java">
 

/*

* Permission is hereby granted, free of charge, to any person obtaining a copy of 
* this software and associated documentation files (the "Software"), to deal in 
* the Software without restriction, including without limitation the rights to 
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
* SOFTWARE.
*/

public class ArrayCopy {

 public static byte[] int2byte(int[]src) {
   int srcLength = src.length;
   byte[]dst = new byte[srcLength << 2];
   
   for (int i=0; i<srcLength; i++) {
       int x = src[i];
       int j = i << 2;
       dst[j++] = (byte) ((x >>> 0) & 0xff);           
       dst[j++] = (byte) ((x >>> 8) & 0xff);
       dst[j++] = (byte) ((x >>> 16) & 0xff);
       dst[j++] = (byte) ((x >>> 24) & 0xff);
   }
   return dst;

} }


 </source>
   
  
 
  



Return a new byte array containing a sub-portion of the source array

   <source lang="java">
 

/**********************************************************************************

*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
*                  Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
*      http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/

/**

* Byte utilities
*/

public class ByteUtils {

 /**
  * Return a new byte array containing a sub-portion of the source array
  * 
  * @param srcBegin
  *          The beginning index (inclusive)
  * @return The new, populated byte array
  */
 public static byte[] subbytes(byte[] source, int srcBegin) {
   return subbytes(source, srcBegin, source.length);
 }
 /**
  * Return a new byte array containing a sub-portion of the source array
  * 
  * @param srcBegin
  *          The beginning index (inclusive)
  * @param srcEnd
  *          The ending index (exclusive)
  * @return The new, populated byte array
  */
 public static byte[] subbytes(byte[] source, int srcBegin, int srcEnd) {
   byte destination[];
   destination = new byte[srcEnd - srcBegin];
   getBytes(source, srcBegin, srcEnd, destination, 0);
   return destination;
 }
 /**
  * Copies bytes from the source byte array to the destination array
  * 
  * @param source
  *          The source array
  * @param srcBegin
  *          Index of the first source byte to copy
  * @param srcEnd
  *          Index after the last source byte to copy
  * @param destination
  *          The destination array
  * @param dstBegin
  *          The starting offset in the destination array
  */
 public static void getBytes(byte[] source, int srcBegin, int srcEnd, byte[] destination,
     int dstBegin) {
   System.arraycopy(source, srcBegin, destination, dstBegin, srcEnd - srcBegin);
 }

}


 </source>
   
  
 
  



Turn an array of ints into a printable string.

   <source lang="java">
 

import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; /*

  Derby - Class org.apache.derby.iapi.util.PropertyUtil
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to you under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

public class Main {

 /**
  * Turn an array of ints into a printable string. Returns what"s returned
  * in Java 5 by java.util.Arrays.toString(int[]).
  */
 public  static  String  stringify( int[] raw )
 {
     if ( raw == null ) { return "null"; }
     
     StringBuffer    buffer = new StringBuffer();
     int                 count = raw.length;
     buffer.append( "[ " );
     for ( int i = 0; i < count; i++ )
     {
         if ( i > 0 ) { buffer.append( ", " ); }
         buffer.append( raw[ i ] );
     }
     buffer.append( " ]" );
     return buffer.toString();
 }

}


 </source>