Mega Code Archive

 
Categories / Java / Collections Data Structure
 

Dynamic Long Array

/* Copyright (C) 2007  Mobixess Inc. http://www.java-objects-database.com This file is part of the JODB (Java Objects Database) open source project. JODB is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. JODB 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.  */ public class DynamicLongArray {     final static int DEFAULT_CHUNK_SIZE = 256;     final static int DEFAULT_CHUNKS = 16;     private int _chunkSize;     private long[][] _data;     private int _length;     public DynamicLongArray() {         this(DEFAULT_CHUNK_SIZE);     }     public DynamicLongArray(int chunkSize) {         _chunkSize = chunkSize;         _data = new long[DEFAULT_CHUNKS][];     }     public boolean isEmpty() {         return (_length == 0);     }     private void ensureCapacity(int index) {         if (index >= _length) {             int i = index / _chunkSize;             if (i >= _data.length) {                 // grow by 50%                 int new_size = (i * 3) / 2 + 1;                 long[][] newChunk = new long[new_size][];                 System.arraycopy(_data, 0, newChunk, 0, _data.length);                 _data = newChunk;             }             _length = index + 1;         }     }     public long get(int index) {         if (index >= _length) {             throw new IndexOutOfBoundsException("Index " + index                     + " is outside of 0.." + (_length - 1));         }         int i = index / _chunkSize;         int j = index % _chunkSize;         if (_data[i] == null) {             return 0;         } else {             return _data[i][j];         }     }     public void set(int index, long value) {         int i = index / _chunkSize;         int j = index % _chunkSize;         ensureCapacity(index);         if (_data[i] == null) {             _data[i] = new long[_chunkSize];         }         _data[i][j] = value;     }     public int size() {         return _length;     }     public String toString() {         int i;         StringBuffer sb = new StringBuffer(_length * 4);         sb.append('{');         int l = _length - 1;         for (i = 0; i < l; i++) {             sb.append(get(i));             sb.append(',');         }         sb.append(get(i));         sb.append('}');         return sb.toString();     } }