KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > util > ResizableContainer


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.cocoon.util;
18
19 /**
20  * Add-only Container class.
21  *
22  * @author <a HREF="mailto:stefano@apache.org">Stefano Mazzocchi</a>
23  * @version CVS $Id: ResizableContainer.java 30932 2004-07-29 17:35:38Z vgritsenko $
24  */

25 public class ResizableContainer {
26
27     private int pointer = -1;
28     private int size = 0;
29     private Object JavaDoc[] container;
30
31     public ResizableContainer(int initialCapacity){
32         this.container = new Object JavaDoc[initialCapacity];
33     }
34
35     public void add(Object JavaDoc o) {
36         set(++pointer,o);
37     }
38     
39     public void set(int index, Object JavaDoc o) {
40         adjustPointer(index);
41         ensureCapacity(index+1);
42         container[index] = o;
43         size++;
44     }
45     
46     public Object JavaDoc get(int index) {
47         return (index < container.length) ? container[index] : null;
48     }
49
50     public int size() {
51         return size;
52     }
53
54     private void adjustPointer(int newPointer) {
55         this.pointer = Math.max(this.pointer, newPointer);
56     }
57     
58     private void ensureCapacity(int minCapacity) {
59         int oldCapacity = container.length;
60         if (oldCapacity < minCapacity) {
61             Object JavaDoc[] oldContainer = container;
62             int newCapacity = (oldCapacity * 3)/2 + 1;
63             if (newCapacity < minCapacity) {
64                 newCapacity = minCapacity;
65             }
66             container = new Object JavaDoc[newCapacity];
67             System.arraycopy(oldContainer, 0, container, 0, oldContainer.length);
68         }
69     }
70 }
71
Popular Tags