001    /*
002     *  www.ti.bfh.ch
003     *
004     *  Copyright 2007, Berne University of Applied Sciences, 
005     *  School of Engineering and Information Technology
006     *  and individual contributors as indicated by the @authors tag.
007     *
008     *  This is free software; you can redistribute it and/or modify it under the terms of the 
009     *  GNU Lesser General Public License as published by the Free Software Foundation; 
010     *  either version 3 of the License, or (at your option) any later version.
011     *
012     *  This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
013     *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
014     *  See the GNU Lesser General Public License for more details.
015     *
016     *  You should have received a copy of the GNU Lesser General Public License along with this software; 
017     *  if not, see <http://www.gnu.org/licenses/>.
018     *
019     */
020    package ch.bfh.algo.core.sequence;
021    
022    
023    
024    public class DefaultGenericArrayStrategy<P> implements ArrayStrategy<P>{
025            
026            private ArrayFactory<P> factory;
027            
028            private int enlarge;
029            private int shrink;
030            private int shrinktest;
031            private int initial;
032            
033            public DefaultGenericArrayStrategy(ArrayFactory<P> factory){
034                    this(2,2,factory);
035            }
036    
037            public DefaultGenericArrayStrategy(int enlarge, int shrink, ArrayFactory<P> factory){
038                    this.factory=factory;
039                    this.enlarge=enlarge;
040                    this.shrink=shrink;
041                    this.shrinktest=this.enlarge*this.shrink;
042            }
043    
044            public P[] initialize(int size){
045                    this.initial=size;
046                    return this.factory.createArray(size);
047            }
048    
049            public P[] enlarge(int used, P[] array) {
050                    if(array==null || used<array.length) return array;
051                    else{
052                            P[] a=this.factory.createArray(array.length*this.enlarge);
053                            for(int i=0;i<used;i++) a[i]=array[i];
054                            return a;
055                    }
056            }
057    
058            public P[] shrink(int used, P[] array) {
059                    if(array==null || array.length<=this.initial || array.length<=used*this.shrinktest) return array;
060                    else{
061                            P[] a=this.factory.createArray(array.length/this.shrink);
062                            for(int i=0;i<used;i++) a[i]=array[i];
063                            return a;
064                    }
065            }
066    }