HashMap之Java实现

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

  public V search(K key) {

  if (key == null) {

  throw new IllegalArgumentException(”key can not be null”);

  }

  int position = index(key);

  Node<K, V> node = buckets[position];

  while (node != null) {

  if (node.key.equals(key)) {

  return node.value;

  }

  node = node.next;

  }

  return null;

  }

  public int size() {

  return size;

  }

  public boolean isEmpty() {

  return size == 0;

  }

  @Override

  public String toString() {

  StringBuffer buffer = new StringBuffer();

  buffer.append(”{“);

  for (int i = 0; i < capacity; i++) {

  Node<K, V> node = buckets[i];

  while (node != null) {

  buffer.append(node.key + “:” + node.value + “, “);

  node = node.next;

  }

  }

  if (buffer.length() > 1) {

  buffer.delete(buffer.length() – 2, buffer.length());

  }

  buffer.append(”}”);

  return buffer.toString();

  }

  private int index(K key) {

  int hashCode = key.hashCode();

  double temp = hashCode * A;

  double digit = temp – Math.floor(temp);

  return (int) Math.floor(digit * capacity);

  }

  static class Node<K, V> {

  private final K key;

  private V value;

  private Node<K, V> next;

  public Node(K key, V value) {

  this.key = key;

  this.value = value;

  }

  public V getValue() {

  return value;

  }

  public void setValue(V value) {

  this.value = value;

  }

  public Node<K, V> getNext() {

  return next;

  }

  public void setNext(Node<K, V> next) {

  this.next = next;

  }

  public K getKey() {

  return key;

  }

  }

  public static void main(String[] args) {

  HashMap<STRING, String> map = new HashMap<STRING, String>();

  map.put(”001″, “James”);

  map.put(”002″, “Antony”);

  map.put(”003″, “Bosh”);

  map.put(”004″, “Wade”);

  map.put(”004″, “WestBrook”);

  System.out.println(map);

  System.out.println(map.size());

  System.out.println(map.search(”004″));

  }

  }

[1][2]

你不勇敢,没人替你坚强。

HashMap之Java实现

相关文章:

你感兴趣的文章:

标签云: