Mega Code Archive

 
Categories / Java / Collections Data Structure
 

Inserts an Object into an Object array at the index position

import java.lang.reflect.Array;      /*********************************************************************      * Array manipulation for Java 1.1+.      *      * <p>      * Java 1.1 compatible.      * </p>      *      * @see      *   ArrayLib2      *      * @version      *   2003-04-07      * @since      *   2001-04-06      * @author      *   <a href="http://croftsoft.com/">David Wallace Croft</a>*/ public class Util{     /*********************************************************************     * Inserts an Object into an Object array at the index position.     *     * <p>     * Example:     * <code>     * <pre>     * String [ ]  stringArray     *   = ( String [ ] ) ArrayLib.insert ( new String [ ] { }, "", 0 );     * </pre>     * </code>     * </p>     *     * @throws NullArgumentException     *     *   If objectArray or o is null.     *     * @throws IndexOutOfBoundsException     *     *   If index < 0 or index > objectArray.length.     *     * @return     *     *   Returns a new array with the same component type as the old array.     *********************************************************************/     public static Object [ ]  insert (       Object [ ]  objectArray,       Object      o,       int         index )     //////////////////////////////////////////////////////////////////////     {       if ( ( index < 0                  )         || ( index > objectArray.length ) )       {         throw new IndexOutOfBoundsException (           "index out of range:  " + index );       }       Object [ ]  newObjectArray = ( Object [ ] ) Array.newInstance (         objectArray.getClass ( ).getComponentType ( ),         objectArray.length + 1 );       System.arraycopy ( objectArray, 0, newObjectArray, 0, index );       newObjectArray [ index ] = o;       System.arraycopy ( objectArray, index, newObjectArray, index + 1,         objectArray.length - index );       return newObjectArray;     } }