001: package mlsub.typing.lowlevel;
002:
003: /**
004: * A growable array of integers.
005: * Same API as for TVect
006: *
007: * @version $Revision: 1.2 $, $Date: 2003/01/28 10:21:27 $
008: * @author Alexandre Frey.
009: **/
010: public class IntVect {
011: private int elementCount;
012: private int[] elementData;
013: private int capacityIncrement;
014: private int defaultValue;
015:
016: public IntVect(int initialCapacity, int capacityIncrement,
017: int defaultValue) {
018: this .elementData = new int[initialCapacity];
019: this .capacityIncrement = capacityIncrement;
020: this .defaultValue = defaultValue;
021: }
022:
023: public IntVect(int initialCapacity, int defaultValue) {
024: this (initialCapacity, 0, defaultValue);
025: }
026:
027: public IntVect(int defaultValue) {
028: this (10, defaultValue);
029: }
030:
031: public IntVect() {
032: this (0);
033: }
034:
035: // picked from Vector.java
036: private void ensureCapacity(int minCapacity) {
037: int oldCapacity = elementData.length;
038: if (minCapacity > oldCapacity) {
039: int[] oldData = elementData;
040: int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement)
041: : (oldCapacity * 2);
042: if (newCapacity < minCapacity) {
043: newCapacity = minCapacity;
044: }
045: elementData = new int[newCapacity];
046: System.arraycopy(oldData, 0, elementData, 0, elementCount);
047: if (defaultValue != 0) {
048: for (int i = oldCapacity; i < newCapacity; i++) {
049: elementData[i] = defaultValue;
050: }
051: }
052: }
053: }
054:
055: public void setSize(int newSize, int defaultValue) {
056: if (newSize > elementCount) {
057: ensureCapacity(newSize);
058: for (int i = elementCount; i < newSize; i++) {
059: elementData[i] = defaultValue;
060: }
061: } else {
062: for (int i = elementCount; i < newSize; i++) {
063: elementData[i] = defaultValue;
064: }
065: }
066: elementCount = newSize;
067: }
068:
069: public void add(int x) {
070: ensureCapacity(elementCount + 1);
071: elementData[elementCount++] = x;
072: }
073:
074: private void checkIndex(int index) {
075: if (index >= elementCount) {
076: throw new ArrayIndexOutOfBoundsException(index + " >= "
077: + elementCount);
078: }
079: if (index < 0) {
080: throw new ArrayIndexOutOfBoundsException(index + " < 0");
081: }
082: }
083:
084: public int get(int index) {
085: // checkIndex(index);//only useful for debuging
086: return elementData[index];
087: }
088:
089: public void set(int index, int x) {
090: // checkIndex(index);//only useful for debuging
091: elementData[index] = x;
092: }
093:
094: public int[] toArray() {
095: int[] result = new int[elementCount];
096: System.arraycopy(elementData, 0, result, 0, elementCount);
097: return result;
098: }
099:
100: public int size() {
101: return elementCount;
102: }
103:
104: public String toString() {
105: return Misc.arrayToString(elementData, elementCount, "[", ", ",
106: "]");
107: }
108: }
|