/** * Puts a key/value pair into the array, optimizing for the case where the key is greater than all * existing keys in the array. */ public int append(long key, long value) { if (mSize != 0 && key <= mKeys[mSize - 1]) { return put(key, value); } if (mGarbage && mSize >= mKeys.length) { gc(); } int pos = mSize; if (pos >= mKeys.length) { int n = Helper.idealIntArraySize(pos + 1); long[] nkeys = new long[n]; long[] nvalues = new long[n]; System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); System.arraycopy(mValues, 0, nvalues, 0, mValues.length); mKeys = nkeys; mValues = nvalues; } mKeys[pos] = key; mValues[pos] = value; mSize = pos + 1; return pos; }
/** * Creates a new SparseLongLongArray containing no mappings that will not require any additional * memory allocation to store the specified number of mappings. */ public SparseLongLongArray(int cap) { try { cap = Helper.idealIntArraySize(cap); mKeys = new long[cap]; mValues = new long[cap]; mSize = 0; } catch (OutOfMemoryError err) { System.err.println("requested capacity " + cap); throw err; } }
/** * Adds a mapping from the specified key to the specified value, replacing the previous mapping * from the specified key if there was one. */ public int put(long key, long value) { int i = binarySearch(mKeys, 0, mSize, key); if (i >= 0) { mValues[i] = value; } else { i = ~i; if (i < mSize && mValues[i] == DELETED) { mKeys[i] = key; mValues[i] = value; return i; } if (mGarbage && mSize >= mKeys.length) { gc(); // Search again because indices may have changed. i = ~binarySearch(mKeys, 0, mSize, key); } if (mSize >= mKeys.length) { int n = Helper.idealIntArraySize(mSize + 1); long[] nkeys = new long[n]; long[] nvalues = new long[n]; System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); System.arraycopy(mValues, 0, nvalues, 0, mValues.length); mKeys = nkeys; mValues = nvalues; } if (mSize - i != 0) { System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); System.arraycopy(mValues, i, mValues, i + 1, mSize - i); } mKeys[i] = key; mValues[i] = value; mSize++; } return i; }