hashMap僞代碼


hashMap原理的僞代碼

V put(K k , V v) {
  int hashCode = hashCode(k);
  Node node = new Node(k, v);
  if (table[hashCode] == null) {
    table[hashCode] = node;
  } else {
    Node firstNode = table[hashCode];
    Node existNode;
    if (firstNode.equals(node)) {
        existNode = firstNode;
    } else if (firstNode instanceOf treeNode) {
        //insert into tree
    } else {
      int linkedListLength;
      Node currentNode = firstNode.next();
      while(currentNode != null) {
          linkedListLength ++ ;
          if (currentNode.hashCode == hashCode && currentNode.Key.equals(K)) {
              existNode = currentNode;
              break;
          }
          currentNode = currentNode.next();
      }
      currentNode.next = node;
      if (linkedListLength >=8 ) {
          treeifyBin(table);
      }
    }
    if (existNode != null) {
        V oldValue = existNode.value;
        existNode.value = v;
        return oldValue;
    }
  }
  return null;
}



V get(K key) {
    int index = hashCode(key);
    Node firstNode = table[index];
    if (firstNode.Key.equals(key)) {
      return fistNode;
    }
    Node currentNode = firstNode;
    while(currentNode != null) {
      if (currentNode instanceOf TreeNode) {
          return currentNode.getTreeNode(key);
      }
      if (currentNode.Key.equals(key)) {
        return currentNode;
      }
      currentNode = currentNode.next();
    }
    return null;
}

 

發佈了247 篇原創文章 · 獲贊 24 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章