Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
What issues / pitfalls must be considered when overriding equals and hashCode?
I have a Map which is to be modified by several threads concurrently. There seem to be three different synchronized Map implementations in the Java API: Hashtable Collections.synchronizedMap(Map) ConcurrentHashMap From what I understand, Hashtable is an old implementation (extending the obsolete Dictionary class), which has been adapted later to fit the Map interface. While it is synchron...
I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times. Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is...
What is null? Is null an instance of anything? What set does null belong to? How is it represented in the memory?
I just noticed that java.util.Observable is a concrete class. Since the purpose of Observable is to be extended, this seems rather odd to me. Is there a reason why it was implemented this way? I found this article which says that The observable is a concrete class, so the class deriving from it must be determined upfront, as Java allows only single inheritance. But that doesn't really e...
Does MATLAB have any support for hash tables? Some background I am working on a problem in Matlab that requires a scale-space representation of an image. To do this I create a 2-D Gaussian filter with variance sigma*s^k for k in some range., and then I use each one in turn to filter the image. Now, I want some sort of mapping from k to the filtered image. If k were always an integer, I'd ...
I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store. I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries. I know there is a lot of overhead in general with list...
I was asked this question recently during my job interview, and I couldn't answer it. So, what is the most used pattern in java.io and how is it used? What are other patterns used in common java libraries?
What is the difference between a Hashtable and Properties?
Is it possible to have multiple values for the same key in a hash table? If not, can you suggest any such class or interface which could be used?
This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. I'd prefer to do it RIGHT. :) Here is the situation: I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look li...
I'm programming a java application that reads strictly text files (.txt). These files can contain upwards of 120,000 words. The application needs to store all +120,000 words. It needs to name them word_1, word_2, etc. And it also needs to access these words to perform various methods on them. The methods all have to do with Strings. For instance, a method will be called to say how many lett...
In C# Dictionary<String, String> dictionary = new Dictionary<String, String>(); In Java, this errors with Cannot instantiate the type Dictionary What could be wrong? In my code this follows with dictionary.put("vZip", jsonUdeals.getString("vZip")); I know this sounds too trivial. But I am at a loss! If Dictionary doesn't do it(which I strongly suspect by now), then ...
I was reading the Java api docs on Hashtable class and came across several questions. In the doc, it says "Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. " I tried the following code myself Hashtable<String, Integer> me = new Hashtable<String, Integer>(); me.put("one", new Integer(1...
If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined?
Hashtable does not allow null keys or values, while HashMap allows null values and 1 null key. Questions: Why is this so? How is it useful to have such a key and values in HashMap?
I have hastable htmlcontent is html string of urlstring . I want to write hastable into a .text file . Can you suget me a sulution ?
If a Hashtable is of size 8 originally and we hit the load factor and it grows double the size. How is get still able to retrieve the original values ... so say we have a hash function key(8) transforms into 12345 as the hash value which we mod by 8 and we get the index 7 ... now when the hash table size grows to 16 ...for key(8) we get 12345 .. if we mod it by 16 we will get a different answer...
Sorry of the title is a little bit confusing. What I need to do is read a text file with a bunch of cities and states on separate lines like this: Salem, Oregon St. George, Utah Augusta, Maine Portland, Maine Jefferson City, Missouri Kansas City, Missouri Portland, Oregon Salt Lake City, Utah And then make an output from that like this: Maine: Augusta, Portland Missouri: Jefferson City, Kan...
I want to delete key and value which is stored in a property file. How can i do that????
New to hashtables with a simple question. For some reason googling hasn't gotten me a straight answer. Say I've got an <int,String> hashtable set up: myHashtable.put(1,"bird"); myHashtable.put(2,"iguana"); and I want to change "bird" to "fish" (and leave the index the same). Can I just do a simple put, or do I need to delete the entry, or what? While we're at it, for a simple arr...
   /*
    * Copyright 1994-2006 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  package java.util;
  import java.io.*;

This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

The initial capacity controls a tradeoff between wasted space and the need for rehash operations, which are time-consuming. No rehash operations will ever occur if the initial capacity is greater than the maximum number of entries the Hashtable will contain divided by its load factor. However, setting the initial capacity too high can waste space.

If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

This example creates a hashtable of numbers. It uses the names of the numbers as keys:

   Hashtable<String, Integer> numbers
     = new Hashtable<String, Integer>();
   numbers.put("one", 1);
   numbers.put("two", 2);
   numbers.put("three", 3);

To retrieve a number, use the following code:

   Integer n = numbers.get("two");
   if (n != null) {
     System.out.println("two = " + n);
   }

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable's keys and elements methods are not fail-fast.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized.

Author(s):
Arthur van Hoff
Josh Bloch
Neal Gafter
Since:
JDK1.0
See also:
java.lang.Object.equals(java.lang.Object)
java.lang.Object.hashCode()
rehash()
Collection
Map
HashMap
TreeMap
 
 public class Hashtable<K,V>
     extends Dictionary<K,V>
     implements Map<K,V>, Cloneablejava.io.Serializable {

    
The hash table data.
 
     private transient Entry[] table;

    
The total number of entries in the hash table.
 
     private transient int count;

    
The table is rehashed when its size exceeds this threshold. (The value of this field is (int)(capacity * loadFactor).)

Serial:
 
     private int threshold;

    
The load factor for the hashtable.

Serial:
 
     private float loadFactor;

    
The number of times this Hashtable has been structurally modified Structural modifications are those that change the number of entries in the Hashtable or otherwise modify its internal structure (e.g., rehash). This field is used to make iterators on Collection-views of the Hashtable fail-fast. (See ConcurrentModificationException).
 
     private transient int modCount = 0;

    
use serialVersionUID from JDK 1.0.2 for interoperability
 
     private static final long serialVersionUID = 1421746759512286392L;

    
Constructs a new, empty hashtable with the specified initial capacity and the specified load factor.

Parameters:
initialCapacity the initial capacity of the hashtable.
loadFactor the load factor of the hashtable.
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero, or if the load factor is nonpositive.
 
     public Hashtable(int initialCapacityfloat loadFactor) {
         if (initialCapacity < 0)
             throw new IllegalArgumentException("Illegal Capacity: "+
                                                initialCapacity);
         if (loadFactor <= 0 || Float.isNaN(loadFactor))
             throw new IllegalArgumentException("Illegal Load: "+loadFactor);
 
         if (initialCapacity==0)
             initialCapacity = 1;
         this. = loadFactor;
          = new Entry[initialCapacity];
          = (int)(initialCapacity * loadFactor);
     }

    
Constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75).

Parameters:
initialCapacity the initial capacity of the hashtable.
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero.
 
     public Hashtable(int initialCapacity) {
         this(initialCapacity, 0.75f);
     }

    
Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75).
 
     public Hashtable() {
         this(11, 0.75f);
     }

    
Constructs a new hashtable with the same mappings as the given Map. The hashtable is created with an initial capacity sufficient to hold the mappings in the given Map and a default load factor (0.75).

Parameters:
t the map whose mappings are to be placed in this map.
Throws:
java.lang.NullPointerException if the specified map is null.
Since:
1.2
 
     public Hashtable(Map<? extends K, ? extends V> t) {
         this(Math.max(2*t.size(), 11), 0.75f);
         putAll(t);
     }

    
Returns the number of keys in this hashtable.

Returns:
the number of keys in this hashtable.
 
     public synchronized int size() {
         return ;
     }

    
Tests if this hashtable maps no keys to values.

Returns:
true if this hashtable maps no keys to values; false otherwise.
 
     public synchronized boolean isEmpty() {
         return  == 0;
     }

    
Returns an enumeration of the keys in this hashtable.

Returns:
an enumeration of the keys in this hashtable.
See also:
Enumeration
elements()
keySet()
Map
 
     public synchronized Enumeration<K> keys() {
         return this.<K>getEnumeration();
     }

    
Returns an enumeration of the values in this hashtable. Use the Enumeration methods on the returned object to fetch the elements sequentially.

Returns:
an enumeration of the values in this hashtable.
See also:
Enumeration
keys()
values()
Map
 
     public synchronized Enumeration<V> elements() {
         return this.<V>getEnumeration();
     }

    
Tests if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method.

Note that this method is identical in functionality to containsValue, (which is part of the Map interface in the collections framework).

Parameters:
value a value to search for
Returns:
true if and only if some key maps to the value argument in this hashtable as determined by the equals method; false otherwise.
Throws:
java.lang.NullPointerException if the value is null
 
     public synchronized boolean contains(Object value) {
         if (value == null) {
             throw new NullPointerException();
         }
 
         Entry tab[] = ;
         for (int i = tab.length ; i-- > 0 ;) {
             for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {
                 if (e.value.equals(value)) {
                     return true;
                 }
             }
         }
         return false;
     }

    
Returns true if this hashtable maps one or more keys to this value.

Note that this method is identical in functionality to contains(java.lang.Object) (which predates the Map interface).

Parameters:
value value whose presence in this hashtable is to be tested
Returns:
true if this map maps one or more keys to the specified value
Throws:
java.lang.NullPointerException if the value is null
Since:
1.2
 
     public boolean containsValue(Object value) {
         return contains(value);
     }

    
Tests if the specified object is a key in this hashtable.

Parameters:
key possible key
Returns:
true if and only if the specified object is a key in this hashtable, as determined by the equals method; false otherwise.
Throws:
java.lang.NullPointerException if the key is null
See also:
contains(java.lang.Object)
 
     public synchronized boolean containsKey(Object key) {
         Entry tab[] = ;
         int hash = key.hashCode();
         int index = (hash & 0x7FFFFFFF) % tab.length;
         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
             if ((e.hash == hash) && e.key.equals(key)) {
                 return true;
             }
         }
         return false;
     }

    
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

More formally, if this map contains a mapping from a key k to a value v such that (key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

Parameters:
key the key whose associated value is to be returned
Returns:
the value to which the specified key is mapped, or null if this map contains no mapping for the key
Throws:
java.lang.NullPointerException if the specified key is null
See also:
put(java.lang.Object,java.lang.Object)
 
     public synchronized V get(Object key) {
         Entry tab[] = ;
         int hash = key.hashCode();
         int index = (hash & 0x7FFFFFFF) % tab.length;
         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
             if ((e.hash == hash) && e.key.equals(key)) {
                 return e.value;
             }
         }
         return null;
     }

    
Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently. This method is called automatically when the number of keys in the hashtable exceeds this hashtable's capacity and load factor.
 
     protected void rehash() {
         int oldCapacity = .;
         Entry[] oldMap = ;
 
         int newCapacity = oldCapacity * 2 + 1;
         Entry[] newMap = new Entry[newCapacity];
 
         ++;
          = (int)(newCapacity * );
          = newMap;
 
         for (int i = oldCapacity ; i-- > 0 ;) {
             for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
                 Entry<K,V> e = old;
                 old = old.next;
 
                 int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                 e.next = newMap[index];
                 newMap[index] = e;
             }
         }
     }

    
Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null.

The value can be retrieved by calling the get method with a key that is equal to the original key.

Parameters:
key the hashtable key
value the value
Returns:
the previous value of the specified key in this hashtable, or null if it did not have one
Throws:
java.lang.NullPointerException if the key or value is null
See also:
java.lang.Object.equals(java.lang.Object)
get(java.lang.Object)
 
     public synchronized V put(K key, V value) {
         // Make sure the value is not null
         if (value == null) {
             throw new NullPointerException();
         }
 
         // Makes sure the key is not already in the hashtable.
         Entry tab[] = ;
         int hash = key.hashCode();
         int index = (hash & 0x7FFFFFFF) % tab.length;
         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
             if ((e.hash == hash) && e.key.equals(key)) {
                 V old = e.value;
                 e.value = value;
                 return old;
             }
         }
 
         ++;
         if ( >= ) {
             // Rehash the table if the threshold is exceeded
             rehash();
 
             tab = ;
             index = (hash & 0x7FFFFFFF) % tab.length;
         }
 
         // Creates the new entry.
         Entry<K,V> e = tab[index];
         tab[index] = new Entry<K,V>(hashkeyvaluee);
         ++;
         return null;
     }

    
Removes the key (and its corresponding value) from this hashtable. This method does nothing if the key is not in the hashtable.

Parameters:
key the key that needs to be removed
Returns:
the value to which the key had been mapped in this hashtable, or null if the key did not have a mapping
Throws:
java.lang.NullPointerException if the key is null
 
     public synchronized V remove(Object key) {
         Entry tab[] = ;
         int hash = key.hashCode();
         int index = (hash & 0x7FFFFFFF) % tab.length;
         for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = ee = e.next) {
             if ((e.hash == hash) && e.key.equals(key)) {
                 ++;
                 if (prev != null) {
                     prev.next = e.next;
                 } else {
                     tab[index] = e.next;
                 }
                 --;
                 V oldValue = e.value;
                 e.value = null;
                 return oldValue;
             }
         }
         return null;
     }

    
Copies all of the mappings from the specified map to this hashtable. These mappings will replace any mappings that this hashtable had for any of the keys currently in the specified map.

Parameters:
t mappings to be stored in this map
Throws:
java.lang.NullPointerException if the specified map is null
Since:
1.2
 
     public synchronized void putAll(Map<? extends K, ? extends V> t) {
         for (Map.Entry<? extends K, ? extends V> e : t.entrySet())
             put(e.getKey(), e.getValue());
     }

    
Clears this hashtable so that it contains no keys.
 
     public synchronized void clear() {
         Entry tab[] = ;
         ++;
         for (int index = tab.length; --index >= 0; )
             tab[index] = null;
          = 0;
     }

    
Creates a shallow copy of this hashtable. All the structure of the hashtable itself is copied, but the keys and values are not cloned. This is a relatively expensive operation.

Returns:
a clone of the hashtable
 
     public synchronized Object clone() {
         try {
             Hashtable<K,V> t = (Hashtable<K,V>) super.clone();
             t.table = new Entry[.];
             for (int i = . ; i-- > 0 ; ) {
                 t.table[i] = ([i] != null)
                     ? (Entry<K,V>) [i].clone() : null;
             }
             t.keySet = null;
             t.entrySet = null;
             t.values = null;
             t.modCount = 0;
             return t;
         } catch (CloneNotSupportedException e) {
             // this shouldn't happen, since we are Cloneable
             throw new InternalError();
         }
     }

    
Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). Each entry is rendered as the key, an equals sign =, and the associated element, where the toString method is used to convert the key and element to strings.

Returns:
a string representation of this hashtable
 
     public synchronized String toString() {
         int max = size() - 1;
         if (max == -1)
             return "{}";
 
         StringBuilder sb = new StringBuilder();
         Iterator<Map.Entry<K,V>> it = entrySet().iterator();
 
         sb.append('{');
         for (int i = 0; ; i++) {
             Map.Entry<K,V> e = it.next();
             K key = e.getKey();
             V value = e.getValue();
             sb.append(key   == this ? "(this Map)" : key.toString());
             sb.append('=');
             sb.append(value == this ? "(this Map)" : value.toString());
 
             if (i == max)
                 return sb.append('}').toString();
             sb.append(", ");
         }
     }
 
 
     private <T> Enumeration<T> getEnumeration(int type) {
         if ( == 0) {
             return Collections.emptyEnumeration();
         } else {
             return new Enumerator<T>(typefalse);
         }
     }
 
     private <T> Iterator<T> getIterator(int type) {
         if ( == 0) {
             return Collections.emptyIterator();
         } else {
             return new Enumerator<T>(typetrue);
         }
     }
 
     // Views
 
    
Each of these fields are initialized to contain an instance of the appropriate view the first time this view is requested. The views are stateless, so there's no reason to create more than one of each.
 
     private transient volatile Set<K> keySet = null;
     private transient volatile Set<Map.Entry<K,V>> entrySet = null;
     private transient volatile Collection<V> values = null;

    
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Since:
1.2
 
     public Set<K> keySet() {
         if ( == null)
              = Collections.synchronizedSet(new KeySet(), this);
         return ;
     }
 
     private class KeySet extends AbstractSet<K> {
         public Iterator<K> iterator() {
             return getIterator();
         }
         public int size() {
             return ;
         }
         public boolean contains(Object o) {
             return containsKey(o);
         }
         public boolean remove(Object o) {
             return Hashtable.this.remove(o) != null;
         }
         public void clear() {
             Hashtable.this.clear();
         }
     }

    
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Since:
1.2
 
     public Set<Map.Entry<K,V>> entrySet() {
         if (==null)
              = Collections.synchronizedSet(new EntrySet(), this);
         return ;
     }
 
     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
         public Iterator<Map.Entry<K,V>> iterator() {
             return getIterator();
         }
 
         public boolean add(Map.Entry<K,V> o) {
             return super.add(o);
         }
 
         public boolean contains(Object o) {
             if (!(o instanceof Map.Entry))
                 return false;
             Map.Entry entry = (Map.Entry)o;
             Object key = entry.getKey();
             Entry[] tab = ;
             int hash = key.hashCode();
             int index = (hash & 0x7FFFFFFF) % tab.length;
 
             for (Entry e = tab[index]; e != nulle = e.next)
                 if (e.hash==hash && e.equals(entry))
                     return true;
             return false;
         }
 
         public boolean remove(Object o) {
             if (!(o instanceof Map.Entry))
                 return false;
             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
             K key = entry.getKey();
             Entry[] tab = ;
             int hash = key.hashCode();
             int index = (hash & 0x7FFFFFFF) % tab.length;
 
             for (Entry<K,V> e = tab[index], prev = nulle != null;
                  prev = ee = e.next) {
                 if (e.hash==hash && e.equals(entry)) {
                     ++;
                     if (prev != null)
                         prev.next = e.next;
                     else
                         tab[index] = e.next;
 
                     --;
                     e.value = null;
                     return true;
                 }
             }
             return false;
         }
 
         public int size() {
             return ;
         }
 
         public void clear() {
             Hashtable.this.clear();
         }
     }

    
Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Since:
1.2
 
     public Collection<V> values() {
         if (==null)
              = Collections.synchronizedCollection(new ValueCollection(),
                                                         this);
         return ;
     }
 
     private class ValueCollection extends AbstractCollection<V> {
         public Iterator<V> iterator() {
             return getIterator();
         }
         public int size() {
             return ;
         }
         public boolean contains(Object o) {
             return containsValue(o);
         }
         public void clear() {
             Hashtable.this.clear();
         }
     }
 
     // Comparison and hashing
 
    
Compares the specified Object with this Map for equality, as per the definition in the Map interface.

Parameters:
o object to be compared for equality with this hashtable
Returns:
true if the specified Object is equal to this Map
Since:
1.2
See also:
Map.equals(java.lang.Object)
 
     public synchronized boolean equals(Object o) {
         if (o == this)
             return true;
 
         if (!(o instanceof Map))
             return false;
         Map<K,V> t = (Map<K,V>) o;
         if (t.size() != size())
             return false;
 
         try {
             Iterator<Map.Entry<K,V>> i = entrySet().iterator();
             while (i.hasNext()) {
                 Map.Entry<K,V> e = i.next();
                 K key = e.getKey();
                 V value = e.getValue();
                 if (value == null) {
                     if (!(t.get(key)==null && t.containsKey(key)))
                         return false;
                 } else {
                     if (!value.equals(t.get(key)))
                         return false;
                 }
             }
         } catch (ClassCastException unused)   {
             return false;
         } catch (NullPointerException unused) {
             return false;
         }
 
         return true;
     }

    
Returns the hash code value for this Map as per the definition in the Map interface.

Since:
1.2
See also:
Map.hashCode()
 
     public synchronized int hashCode() {
         /*
          * This code detects the recursion caused by computing the hash code
          * of a self-referential hash table and prevents the stack overflow
          * that would otherwise result.  This allows certain 1.1-era
          * applets with self-referential hash tables to work.  This code
          * abuses the loadFactor field to do double-duty as a hashCode
          * in progress flag, so as not to worsen the space performance.
          * A negative load factor indicates that hash code computation is
          * in progress.
          */
         int h = 0;
         if ( == 0 ||  < 0)
             return h;  // Returns zero
 
          = -;  // Mark hashCode computation in progress
         Entry[] tab = ;
         for (int i = 0; i < tab.lengthi++)
             for (Entry e = tab[i]; e != nulle = e.next)
                 h += e.key.hashCode() ^ e.value.hashCode();
          = -;  // Mark hashCode computation complete
 
         return h;
     }

    
Save the state of the Hashtable to a stream (i.e., serialize it).

SerialData:
The capacity of the Hashtable (the length of the bucket array) is emitted (int), followed by the size of the Hashtable (the number of key-value mappings), followed by the key (Object) and value (Object) for each key-value mapping represented by the Hashtable The key-value mappings are emitted in no particular order.
 
     private synchronized void writeObject(java.io.ObjectOutputStream s)
         throws IOException
     {
         // Write out the length, threshold, loadfactor
         s.defaultWriteObject();
 
         // Write out length, count of elements and then the key/value objects
         s.writeInt(.);
         s.writeInt();
         for (int index = .-1; index >= 0; index--) {
             Entry entry = [index];
 
             while (entry != null) {
                 s.writeObject(entry.key);
                 s.writeObject(entry.value);
                 entry = entry.next;
             }
         }
     }

    
Reconstitute the Hashtable from a stream (i.e., deserialize it).
 
     private void readObject(java.io.ObjectInputStream s)
          throws IOExceptionClassNotFoundException
     {
         // Read in the length, threshold, and loadfactor
         s.defaultReadObject();
 
         // Read the original length of the array and number of elements
         int origlength = s.readInt();
         int elements = s.readInt();
 
         // Compute new size with a bit of room 5% to grow but
         // no larger than the original size.  Make the length
         // odd if it's large enough, this helps distribute the entries.
         // Guard against the length ending up zero, that's not valid.
         int length = (int)(elements * ) + (elements / 20) + 3;
         if (length > elements && (length & 1) == 0)
             length--;
         if (origlength > 0 && length > origlength)
             length = origlength;
 
         Entry[] table = new Entry[length];
          = 0;
 
         // Read the number of elements and then all the key/value objects
         for (; elements > 0; elements--) {
             K key = (K)s.readObject();
             V value = (V)s.readObject();
             // synch could be eliminated for performance
             reconstitutionPut(tablekeyvalue);
         }
         this. = table;
     }

    
The put method used by readObject. This is provided because put is overridable and should not be called in readObject since the subclass will not yet be initialized.

This differs from the regular put method in several ways. No checking for rehashing is necessary since the number of elements initially in the table is known. The modCount is not incremented because we are creating a new instance. Also, no return value is needed.

 
     private void reconstitutionPut(Entry[] tab, K key, V value)
         throws StreamCorruptedException
     {
         if (value == null) {
             throw new java.io.StreamCorruptedException();
         }
         // Makes sure the key is not already in the hashtable.
         // This should not happen in deserialized version.
         int hash = key.hashCode();
         int index = (hash & 0x7FFFFFFF) % tab.length;
         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
             if ((e.hash == hash) && e.key.equals(key)) {
                 throw new java.io.StreamCorruptedException();
             }
         }
         // Creates the new entry.
         Entry<K,V> e = tab[index];
         tab[index] = new Entry<K,V>(hashkeyvaluee);
         ++;
     }

    
Hashtable collision list.
 
     private static class Entry<K,V> implements Map.Entry<K,V> {
         int hash;
         K key;
         V value;
         Entry<K,V> next;
 
         protected Entry(int hash, K key, V valueEntry<K,V> next) {
             this. = hash;
             this. = key;
             this. = value;
             this. = next;
         }
 
         protected Object clone() {
             return new Entry<K,V>(,
                                   (==null ? null : (Entry<K,V>) .clone()));
         }
 
         // Map.Entry Ops
 
         public K getKey() {
             return ;
         }
 
         public V getValue() {
             return ;
         }
 
         public V setValue(V value) {
             if (value == null)
                 throw new NullPointerException();
 
             V oldValue = this.;
             this. = value;
             return oldValue;
         }
 
         public boolean equals(Object o) {
             if (!(o instanceof Map.Entry))
                 return false;
             Map.Entry e = (Map.Entry)o;
 
             return (==null ? e.getKey()==null : .equals(e.getKey())) &&
                (==null ? e.getValue()==null : .equals(e.getValue()));
         }
 
         public int hashCode() {
             return  ^ (==null ? 0 : .hashCode());
         }
 
         public String toString() {
             return .toString()+"="+.toString();
         }
     }
 
     // Types of Enumerations/Iterations
     private static final int KEYS = 0;
     private static final int VALUES = 1;
     private static final int ENTRIES = 2;

    
A hashtable enumerator class. This class implements both the Enumeration and Iterator interfaces, but individual instances can be created with the Iterator methods disabled. This is necessary to avoid unintentionally increasing the capabilities granted a user by passing an Enumeration.
 
     private class Enumerator<T> implements Enumeration<T>, Iterator<T> {
         Entry[] table = Hashtable.this.;
         int index = .;
         Entry<K,V> entry = null;
         Entry<K,V> lastReturned = null;
         int type;

        
Indicates whether this Enumerator is serving as an Iterator or an Enumeration. (true -> Iterator).
 
         boolean iterator;

        
The modCount value that the iterator believes that the backing Hashtable should have. If this expectation is violated, the iterator has detected concurrent modification.
        protected int expectedModCount = ;
        Enumerator(int typeboolean iterator) {
            this. = type;
            this. = iterator;
        }
        public boolean hasMoreElements() {
            Entry<K,V> e = ;
            int i = ;
            Entry[] t = ;
            /* Use locals for faster loop iteration */
            while (e == null && i > 0) {
                e = t[--i];
            }
             = e;
             = i;
            return e != null;
        }
        public T nextElement() {
            Entry<K,V> et = ;
            int i = ;
            Entry[] t = ;
            /* Use locals for faster loop iteration */
            while (et == null && i > 0) {
                et = t[--i];
            }
             = et;
             = i;
            if (et != null) {
                Entry<K,V> e =  = ;
                 = e.next;
                return  ==  ? (T)e.key : ( ==  ? (T)e.value : (T)e);
            }
            throw new NoSuchElementException("Hashtable Enumerator");
        }
        // Iterator methods
        public boolean hasNext() {
            return hasMoreElements();
        }
        public T next() {
            if ( != )
                throw new ConcurrentModificationException();
            return nextElement();
        }
        public void remove() {
            if (!)
                throw new UnsupportedOperationException();
            if ( == null)
                throw new IllegalStateException("Hashtable Enumerator");
            if ( != )
                throw new ConcurrentModificationException();
            synchronized(Hashtable.this) {
                Entry[] tab = Hashtable.this.;
                int index = (. & 0x7FFFFFFF) % tab.length;
                for (Entry<K,V> e = tab[index], prev = nulle != null;
                     prev = ee = e.next) {
                    if (e == ) {
                        ++;
                        ++;
                        if (prev == null)
                            tab[index] = e.next;
                        else
                            prev.next = e.next;
                        --;
                         = null;
                        return;
                    }
                }
                throw new ConcurrentModificationException();
            }
        }
    }
New to GrepCode? Check out our FAQ X