001: /*
002: * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
003: *
004: * Licensed under the Aduna BSD-style license.
005: */
006: package org.openrdf.sail.memory.model;
007:
008: import java.util.Arrays;
009:
010: /**
011: * A dedicated data structure for storing MemStatement objects, offering
012: * operations optimized for their use in the memory Sail.
013: */
014: public class MemStatementList {
015:
016: /*-----------*
017: * Variables *
018: *-----------*/
019:
020: private MemStatement[] statements;
021:
022: private int size;
023:
024: /*--------------*
025: * Constructors *
026: *--------------*/
027:
028: /**
029: * Creates a new MemStatementList.
030: */
031: public MemStatementList() {
032: this (4);
033: }
034:
035: public MemStatementList(int capacity) {
036: statements = new MemStatement[capacity];
037: size = 0;
038: }
039:
040: public MemStatementList(MemStatementList other) {
041: this (other.size);
042: addAll(other);
043: }
044:
045: /*---------*
046: * Methods *
047: *---------*/
048:
049: public int size() {
050: return size;
051: }
052:
053: public boolean isEmpty() {
054: return size == 0;
055: }
056:
057: public MemStatement get(int index) {
058: if (index < 0 || index >= size) {
059: if (index < 0) {
060: throw new IndexOutOfBoundsException("index < 0");
061: } else {
062: throw new IndexOutOfBoundsException("index >= size");
063: }
064: }
065:
066: return statements[index];
067: }
068:
069: public void add(MemStatement st) {
070: if (size == statements.length) {
071: // Grow array
072: growArray((size == 0) ? 1 : 2 * size);
073: }
074:
075: statements[size] = st;
076: ++size;
077: }
078:
079: public void addAll(MemStatementList other) {
080: if (size + other.size >= statements.length) {
081: // Grow array
082: growArray(size + other.size);
083: }
084:
085: System.arraycopy(other.statements, 0, statements, size,
086: other.size);
087: size += other.size;
088: }
089:
090: public void remove(int index) {
091: if (index < 0 || index >= size) {
092: if (index < 0) {
093: throw new IndexOutOfBoundsException("index < 0");
094: } else {
095: throw new IndexOutOfBoundsException("index >= size");
096: }
097: }
098:
099: if (index == size - 1) {
100: // Last statement in array
101: statements[index] = null;
102: --size;
103: } else {
104: // Not last statement in array, move last
105: // statement over the one at [index]
106: --size;
107: statements[index] = statements[size];
108: statements[size] = null;
109: }
110: }
111:
112: public void remove(MemStatement st) {
113: for (int i = 0; i < size; ++i) {
114: if (statements[i] == st) {
115: remove(i);
116: return;
117: }
118: }
119: }
120:
121: public void clear() {
122: Arrays.fill(statements, 0, size, null);
123: size = 0;
124: }
125:
126: private void growArray(int newSize) {
127: MemStatement[] newArray = new MemStatement[newSize];
128: System.arraycopy(statements, 0, newArray, 0, size);
129: statements = newArray;
130: }
131: }
|