/** * Removes the mapping from the specified key, if there was any. */ publicvoiddelete(int key){ int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
if (i >= 0) { if (mValues[i] != DELETED) { mValues[i] = DELETED; mGarbage = true; } } }
/** * Adds a mapping from the specified key to the specified value, * replacing the previous mapping from the specified key if there * was one. */ publicvoidput(int key, E value){ int i = ContainerHelpers.binarySearch(mKeys, mSize, key); // key存在,更新value if (i >= 0) { mValues[i] = value; } else { // 取反计算插入位置 i = ~i; // 插入位置非尾部且原来映射已经不存在了,则更新key-value if (i < mSize && mValues[i] == DELETED) { mKeys[i] = key; mValues[i] = value; return; } // 尝试gc一下扩容,重新计算索引 if (mGarbage && mSize >= mKeys.length) { gc();
// Search again because indices may have changed. i = ~ ContainerHelpers.binarySearch(mKeys, mSize, key); } // 扩容,每次扩容都是以2的幂次大小扩容,重新映射 if (mSize >= mKeys.length) { int n = ContainerHelpers.idealIntArraySize(mSize + 1);
int[] nkeys = newint[n]; Object[] nvalues = new Object[n];
/** * Puts a key/value pair into the array, optimizing for the case where * the key is greater than all existing keys in the array. */ publicvoidappend(int key, E value){ // 不是在尾部增加映射 if (mSize != 0 && key <= mKeys[mSize - 1]) { put(key, value); return; }
if (mGarbage && mSize >= mKeys.length) { gc(); }
int pos = mSize; if (pos >= mKeys.length) { int n = ContainerHelpers.idealIntArraySize(pos + 1);
int[] nkeys = newint[n]; Object[] nvalues = new Object[n];