【HashSet和HashMap详解】

Java集合实际是多个引用变量组成的集合,修改引用对象的属性后表现在集合内对象的属性也会相应被修改。但是可验证,如果集合内元素的类型是包装类类型,如Integer,则不满足上述称述。

  对Map而言,每个元素都是key-value的Set集合。HashSet的实现基于HashMap,HashMap的实现用到了Entry数组。于是,可以将电脑公司ghost xp sp3 win7Set集合扩展成Map集合。

  本文主要阅读HashSet和HashMap的JDK源码,了解其实现。

  HashSet源码如下:

  [java]

  public class HashSet<E>

  extends AbstractSet<E>

  implements Set<E>, Cloneable, java.io.Serializable

  {

  static final long serialVersionUID = -5024744406713321676L;

  private transient HashMap<E,Object> map; //基于HashMap

  // Dummy value to associate with an Object in the backing Map

  private static final Object PRESENT = new Object(); //<SPAN style="FONT-FAMILY: Arial, Helvetica, sans-serif">private static final Object</SPAN>

  /**

  * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has

  * default initial capacity (16) and load factor (0.75).

  */

  public HashSet() {

  map = new HashMap<E,Object>();

  }//后面代码略........

  public class HashSet<E>

  extends AbstractSet<E>

  implements Set<E>, Cloneable, java.io.Serializable

  {

  static final long serialVersionUID = -5024744406713321676L;

  private transient HashMap<E,Object> map; //基于HashMap

  // Dummy value to associate with an Object in the backing Map

  private static final Object PRESENT = new Object(); //private static final Object

  /**

  * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has

  * default initial capacity (16) and load factor (0.75).

  */

  public HashSet() {

  map = new HashMap<E,Object>();

  }//后面代码略........可以看到HashSet基于HashMap来实现的,下面来看HashMap的实现。

  下面通过HashMap的两个重要的方法get 和put 方法来认识HashMap。

  [java]

  public V get(Object key) { //HashMap的方法

  if (key == null)

  return getForNullKey();

  int hash = hash(key.hashCode());

  for (Entry<K,V> e = table[indexFor(hash, table.length)];

  e != null;

  e = e.next) {

  Object k;

  if (e.hash == hash && ((k = e.key) == key || key.equals(k))) //此处可见hashCode提升性能!!!!!

  return e.value;

  }

  return null;

  }

  public V get(Object key) { //HashMap的方法

  if (key == null)

  return getForNullKey();

  int hash = hash(key.hashCode());

  for (Entry<K,V> e = table[indexFor(hash, table.length)];

  e != null;

  e = e.next) {

  Object k;

  if (e.hash == hash && ((k = e.key) == key || key.equals(k))) //此处可见hashCode提升性能!!!!!

  return e.value;

  }

  return null;

  }

  [java]

  public V put(K key, V value) { //HashMap的方法

  if (key == null)

  return putForNullKey(value);

  int hash = hash(key.hashCode());

  int i = indexFor(hash, table.length);

  for (Entry<K,V> e = table[i]; e != null; e = e.next) {

  Object k;

  if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { //示例

  V oldValue = e.value;

  e.value = value;

  e.recordAccess(this);

  return oldValue;

  }

  }

posted on 2013-08-30 14:29  挖掘者者者  阅读(283)  评论(0编辑  收藏  举报