// // CheapVector.java // Anneal // // Created by sw on Thu Sep 12 2002. // Copyright (c) 2001 __MyCompanyName__. All rights reserved. // package net.tiac.home.sw.anneal; // CheapVector is a simple growable vector, like Vector, // except it isn't synchronized, or like ArrayList, // except it works in Java 1.1. import java.lang.reflect.*; public class CheapVector { public Object [] v; public int n; public CheapVector ( Object [] v ) { this.v = (Object []) v.clone(); this.n = v.length; } public CheapVector ( Object [] v, int n ) throws Error { if( n > v.length || n < 0 ) { throw new Error( "CheapVector: n not between 0 and v.length" ); } this.v = cloneArray( v, n, n ); this.n = n; } // Make a new array of the same instance type as another: private static Object [] cloneArray ( Object [] original, int allocSize, int copySize ) { Object [] copy = (Object []) Array.newInstance( original.getClass().getComponentType(), allocSize ); System.arraycopy( original, 0, copy, 0, copySize ); return( copy ); } // Instance methods: void makeRoomFor( int n ) { if( n > v.length ) { v = cloneArray( v, (int) Math.max( n, v.length * 2 ), this.n ); } } public CheapVector add( Object o ) { makeRoomFor( n + 1 ); v[ n++ ] = o; return( this ); } public CheapVector set( int i, Object o ) { makeRoomFor( i + 1 ); v[ i ] = o; if( i + 1 > n ) { n = i + 1; // We may be creating a gap of nulls here. } return( this ); } public CheapVector addSubArray( Object [] o, int start, int limit ) { int n = limit - start; makeRoomFor( this.n + n ); System.arraycopy( o, start, v, this.n, n ); this.n += n; return( this ); } public CheapVector addArray( Object [] o ) { return( addSubArray( o, 0, o.length ) ); } public void clear( ) { // Leaving this ready to add() again. v = cloneArray( v, 0, 0 ); n = 0; } // This returns the same array that the vector uses-- // for a while anyway. public Object [] toArray( ) { if( n != v.length ) { v = cloneArray( v, n, n ); } return( v ); } // This definitely returns a separate array: public Object [] toCloneArray( ) { return( cloneArray( v, n, n ) ); } public int [] toIntArray( ) { int [] result = new int [n]; for( int i = 0; i < n; i++ ) { result[i] = ((Integer) v[i]).intValue(); } return( result ); } public Object [] toArrayClear( ) { Object [] result = toArray( ); clear( ); return( result ); } public int [] toIntArrayClear( ) { int [] result = toIntArray( ); clear( ); return( result ); } }