01: /*
02: Copyright (C) 2007 Mobixess Inc. http://www.java-objects-database.com
03:
04: This file is part of the JODB (Java Objects Database) open source project.
05:
06: JODB is free software; you can redistribute it and/or modify it under
07: the terms of version 2 of the GNU General Public License as published
08: by the Free Software Foundation.
09:
10: JODB is distributed in the hope that it will be useful, but WITHOUT ANY
11: WARRANTY; without even the implied warranty of MERCHANTABILITY or
12: FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13: for more details.
14:
15: You should have received a copy of the GNU General Public License along
16: with this program; if not, write to the Free Software Foundation, Inc.,
17: 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18: */
19: package com.mobixess.jodb.util;
20:
21: public class DynamicLongArray {
22: final static int DEFAULT_CHUNK_SIZE = 256;
23: final static int DEFAULT_CHUNKS = 16;
24:
25: private int _chunkSize;
26: private long[][] _data;
27: private int _length;
28:
29: public DynamicLongArray() {
30: this (DEFAULT_CHUNK_SIZE);
31: }
32:
33: public DynamicLongArray(int chunkSize) {
34: _chunkSize = chunkSize;
35: _data = new long[DEFAULT_CHUNKS][];
36: }
37:
38: public boolean isEmpty() {
39: return (_length == 0);
40: }
41:
42: private void ensureCapacity(int index) {
43: if (index >= _length) {
44: int i = index / _chunkSize;
45: if (i >= _data.length) {
46: // grow by 50%
47: int new_size = (i * 3) / 2 + 1;
48: long[][] newChunk = new long[new_size][];
49: System.arraycopy(_data, 0, newChunk, 0, _data.length);
50: _data = newChunk;
51: }
52: _length = index + 1;
53: }
54: }
55:
56: public long get(int index) {
57: if (index >= _length) {
58: throw new IndexOutOfBoundsException("Index " + index
59: + " is outside of 0.." + (_length - 1));
60: }
61: int i = index / _chunkSize;
62: int j = index % _chunkSize;
63: if (_data[i] == null) {
64: return 0;
65: } else {
66: return _data[i][j];
67: }
68: }
69:
70: public void set(int index, long value) {
71: int i = index / _chunkSize;
72: int j = index % _chunkSize;
73: ensureCapacity(index);
74: if (_data[i] == null) {
75: _data[i] = new long[_chunkSize];
76: }
77: _data[i][j] = value;
78: }
79:
80: public int size() {
81: return _length;
82: }
83:
84: public String toString() {
85: int i;
86: StringBuffer sb = new StringBuffer(_length * 4);
87: sb.append('{');
88: int l = _length - 1;
89: for (i = 0; i < l; i++) {
90: sb.append(get(i));
91: sb.append(',');
92: }
93: sb.append(get(i));
94: sb.append('}');
95: return sb.toString();
96: }
97: }
|