KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > versant > core > util > IntArray


1
2 /*
3  * Copyright (c) 1998 - 2005 Versant Corporation
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  * Versant Corporation - initial API and implementation
11  */

12 package com.versant.core.util;
13
14 /**
15  * Growable int[]. This is based com.sosnoski.util.array.IntArray from
16  * Sosnoski Software Solutions, Inc.
17  */

18 public final class IntArray {
19
20     private int[] buf;
21     private int size;
22
23     public IntArray() {
24         this(64);
25     }
26
27     public IntArray(int capacity) {
28         buf = new int[capacity];
29     }
30
31     public int size() {
32         return size;
33     }
34
35     private void ensureCapacity(int len) {
36         if (size + len > buf.length) {
37             int n = buf.length * 3 / 2 + 1;
38             if (size + len > n) {
39                 n = size + len;
40             }
41             int[] a = new int[n];
42             System.arraycopy(buf, 0, a, 0, size);
43             buf = a;
44         }
45     }
46
47     public void add(int v) {
48         ensureCapacity(size + 1);
49         buf[size++] = v;
50     }
51
52     /**
53      * Add a value at a specified index in the array.
54      */

55     public void add(int index, int value) {
56         ensureCapacity(size + 1);
57         if (index == size) {
58             buf[size++] = value;
59         } else {
60             System.arraycopy(buf, index, buf, index + 1, size - index);
61             buf[index] = value;
62         }
63     }
64
65     /**
66      * Constructs and returns a simple array containing the same data as held
67      * in this growable array.
68      */

69     public int[] toArray() {
70         int[] a = new int[size];
71         System.arraycopy(buf, 0, a, 0, size);
72         return a;
73     }
74
75     public void clear() {
76         size = 0;
77     }
78
79     /**
80      * Retrieve the value present at an index position in the array.
81      */

82     public int get(int index) {
83         return buf[index];
84     }
85
86 }
87
88
Popular Tags