`
wuhua
  • 浏览: 2114198 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

A Simple Ordered Hashtable

    博客分类:
  • J2ME
阅读更多

This article illustrates how to implement an ordered hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.

As with typical Hashtables, to successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

There are many instances where you would like to use an ordered Hashtable, for example, to keep your user interface elements ordered, or to keep ordered items from a database or backend while keeping rapid access via Hashtable keys, or to store and access any value you want to access using a key.

This ordered Hashtable is called simple because internally it uses the Legacy collection classes, a Vector to maintain the element's order and a Hashtable to provide hashing capabilities. Because Hashtable and Vector grow differently, the implementation of
[edit]
A Hashtable implementation

SimpleOrderedHashtable is not the most efficient one, but may be good enough for your needs.

/* -----------------------------------------------------------------------------
* SimpleOrderedHashtable.java
* Author: C. Enrique Ortiz
* Copyright (c) 2004-2009 C. Enrique Ortiz <eortiz@j2medeveloper.com>
*
* SimpleOrderedHashtable.java implements a simple Hashtable that is
* chronologically ordered.
*
* This is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version.
*
* Usage & redistributions of source code must retain the above copyright notice.
*
* This software 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
* Lesser General Public License for more details.
*
* You should get a copy of the GNU Lesser General Public License from
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA  02111-1307  USA
* -----------------------------------------------------------------------------
*/
import java.util.Vector;
import java.util.Enumeration;
import java.util.Hashtable;
 
/**
 * Implements an Ordered Hashtable, with elements in
 * chronological order (i.e. insertion order)
 */
public class SimpleOrderedHashtable {
   
    private Vector orderedKeys;
    private Hashtable hashTable;
   
    /**
     * Constructor, creates an SimpleOrderedHashtable.
     */
    public SimpleOrderedHashtable() {
        orderedKeys = new Vector();
        hashTable = new Hashtable();
    }
   
    /**
     * Constructor, creates an SimpleOrderedHashtable.
     * @param initialCapacity is the initial size for the container.
     */
    public SimpleOrderedHashtable(int initialCapacity) {
        orderedKeys = new Vector(initialCapacity);
        hashTable = new Hashtable(initialCapacity);
    }
   
    /**
     * Maps the specified key to the specified value in this SimpleOrderedHashtable.
     * The value can be retrieved by calling the get method with a key that is
     * equal to the original key.
     * @param key is the hashtable key.
     * @param value is the value.
     * @return the previous value of the specified key in this
     * SimpleOrderedHashtable, or null if it did not have one.
     */
    synchronized public Object put(Object key, Object value) {
        int i = orderedKeys.indexOf(key);
        if (i == -1) {
            // Add new name/value pair.
            orderedKeys.addElement(key); // insert (append) to the end of the list
        } else {
            // Replace name/value pair.
            orderedKeys.setElementAt(key, i);
        }
        return hashTable.put(key, value);
    }
   
    /**
     * Returns the value to which the specified key is mapped in this
     * hashtable.
     * @param key is a key in the SimpleOrderedHashtable.
     * @return the value to which the key is mapped in this hashtable; null if
     * the key is not mapped to any value in this hashtable.
     */
    synchronized public Object get(Object key) {
        return hashTable.get(key);
    }
   
    /**
     * Returns an enumeration of the keys in this SimpleOrderedHashtable.
     * @return an enumeration of the keys in this SimpleOrderedHashtable.
     */
    synchronized public Enumeration keys() {
        return orderedKeys.elements();
    }
   
    /**
     * Returns an enumeration of the elements in this SimpleOrderedHashtable.
     * @return an enumeration of the elements in this SimpleOrderedHashtable.
     */
    synchronized public Enumeration elements() {
        int s = hashTable.size();
        Vector elements = new Vector(s);
        for (int i=0; i&lt;s; i++) {
            elements.addElement(elementAt(i));
        }
        return elements.elements();
    }
   
    /**
     * Returns the component at the specified index.
     * @param index is an index into this SimpleOrderedHashtable.
     * @return the &lt;code&gt;Object&lt;/code&gt; component at the specified index.
     * @throws ArrayIndexOutOfBoundsException if index is out of bounds.
     */
    synchronized public Object elementAt(int index)
    throws ArrayIndexOutOfBoundsException {
        Object key = orderedKeys.elementAt(index);
        return hashTable.get(key);
    }
   
    /**
     * Returns the key at the specified index.
     * @param index is an index into this SimpleOrderedHashtable.
     * @return the &lt;code&gt;Object&lt;/code&gt; key at the specified index.
     * @throws ArrayIndexOutOfBoundsException if index is out of bounds.
     */
    synchronized public Object keyAt(int index)
    throws ArrayIndexOutOfBoundsException {
        return orderedKeys.elementAt(index);
    }
   
    /**
     * Returns the index of the specified &lt;code&gt;Object&lt;/code&gt;.
     * @param key is a key in the SimpleOrderedHashtable.
     * @return the index of the specified &lt;code&gt;Object&lt;/code&gt;.
     */
    synchronized public int getIndex(Object key) {
        return orderedKeys.indexOf(key);
    }
   
    /**
     * Removes the key (and its corresponding value) from this hashtable. This
     * method does nothing if the key is not in the hashtable.
     * @param key is the key that needs to be removed.
     */
    synchronized public void remove(Object key) {
        orderedKeys.removeElement(key);
        hashTable.remove(key);
    }
   
    /**
     * Removes an element at the specified index.
     * @param i is the index of the element to remove.
     */
    synchronized public void removeElementAt(int i) {
        Object key = orderedKeys.elementAt(i);
        orderedKeys.removeElementAt(i);
        hashTable.remove(key);
    }
   
    /**
     * Clears this SimpleOrderedHashtable so that it contains no keys.
     */
    synchronized public void clear() {
        orderedKeys.removeAllElements();
        hashTable.clear();
    }
   
    /**
     * Returns the number of components in this SimpleOrderedHashtable.
     * @return the number of components in this vector.
     */
    synchronized public int size() {
        return orderedKeys.size();
    }
   
    /**
     * Recomputes the SimpleOrderedHashtable capacity.
     * @param capacity is the capacity to ensure.
     */
    synchronized public void ensureCapacity(int capacity) {
        orderedKeys.ensureCapacity(capacity);
    }
}

分享到:
评论

相关推荐

    PyPI 官网下载 | orderedset-1.2.tar.gz

    标题中的"PyPI 官网下载 | orderedset-1.2.tar.gz"表明这是一个在Python Package Index (PyPI)上发布的软件包,名为`orderedset-1.2`,并且是以`.tar.gz`格式提供的。PyPI是Python社区用于分发、发现和安装第三方...

    java ordered接口应用

    Java中的`Ordered`接口主要用在需要定义顺序或者排列规则的场景,特别是在Spring框架中,它在Bean的初始化和销毁顺序、AOP切面的执行顺序等方面起到关键作用。`Ordered`接口仅包含一个方法`getOrder()`,返回一个...

    北大POJ2533-Longest Ordered Subsequence【O(nlogn)】

    北大POJ2533-Longest Ordered Subsequence【O(nlogn)】

    Pku acm 第2533题 Longest Ordered Subsequence 代码,有详细的注释

    Pku acm 第2533题 Longest Ordered Subsequence 代码,有详细的注释,动态规划

    Laravel开发-ordered-eloquent

    "Laravel开发-ordered-eloquent"这个项目则是针对Eloquent ORM的一个扩展,旨在实现自动排序查询结果的功能。 这个扩展名为Ordered Eloquent,其主要目标是让开发者在使用Eloquent查询时,能够更加方便地对结果进行...

    M13OrderedDictionary, 带有有序对象和键的NSDictionary.zip

    M13OrderedDictionary, 带有有序对象和键的NSDictionary M13OrderedDictionaryM13OrderedDictionary是NSArray和NSDictionary之间的交叉。 它包含一个有序的对象和键列表。 所有这些都可以通过索引或者键访问。 这里...

    POJ2533-Longest Ordered Subsequence

    标题“POJ2533-Longest Ordered Subsequence”是指北京大学在线判题系统POJ上的一道编程题目,其核心任务是寻找一个序列中最长的有序子序列。描述中的“解题报告+AC代码”表明这个压缩包包含了对这道问题的解答思路...

    OrderedDictionary, 这里库提供OrderedDictionary和MutableOrderedDictionary子类.zip

    OrderedDictionary, 这里库提供OrderedDictionary和MutableOrderedDictionary子类 命令行目存储在NSDictionary中的对象的顺序未定义。 通常,可以以通过一组键/值对循环,并按照插入的顺序返回对象。 这个库提供了两...

    OrderedSet:具有定义顺序的集合

    OrderedSet 静态的,有序的唯一对象集合。 关于 简而言之, OrderedSet是Array和Set的混合体。 像Array一样,它的元素具有定义的顺序,但是它像Set一样在其成员上强制唯一性。 在以下情况下,可以使用OrderedSet...

    OrderedList:OrderedList(与JDK1.7一起编译)

    在Java编程语言中,`OrderedList`是一种特殊的集合类,它不仅提供了集合的基本操作,如添加、删除和查找元素,还特别强调了元素的顺序。标题"OrderedList:OrderedList(与JDK1.7一起编译)"暗示了这个项目或者库是...

    ordered-set:定义自定义迭代顺序的高性能 ES6 Set 子类

    ordered-set是一个高性能的 ES6 Set 子类,它允许控制迭代顺序。 只需为 set 提供要use的排序函数,剩下的就交给它了。 const OrderedSet = require ( 'ordered-set' ) let orderedSet = new OrderedSet ( ) ...

    前端开源库-meteor-ordered-dict

    ** Meteor 有序字典(Ordered Dict)** 在前端开发领域,`meteor-ordered-dict` 是一个非常重要的工具,尤其对于使用 Meteor 框架的开发者来说。Meteor 是一个全栈 JavaScript 开发框架,它允许开发者用同一种语言...

    ordered-set:记住条目顺序的可变集。 Python缺少的数据类型之一

    OrderedSet(['a', 'b', 'r', 'c', 'd']) &gt;&gt;&gt; 'r' in letters True 在OrderedSet中查找条目的索引,或通过其索引查找条目,效率很高。 为了帮助解决该用例, .add()方法返回添加项的索引,无论它是否已经在集合中。 ...

    ORDERED Hint in Complex Searches

    Subject: ORDERED Hint in Complex Searches Doc ID: 408049.1 Type: PROBLEM Modified Date : 08-JUL-2009 Status: PUBLISHED

    Merge two lists of ordered numbers

    Merge two lists of ordered numbers

    Python库 | django-ordered-model-3.1.0.tar.gz

    《深入理解Django有序模型库django-ordered-model》 Django是Python中广泛使用的Web开发框架,它以其高效、简洁的语法和强大的功能而受到开发者们的喜爱。在众多的Django扩展库中,`django-ordered-model`是一个...

    ordered-map:保留插入顺序的C ++哈希映射和哈希集

    "ordered-map"是一个库,它提供了一种特殊的哈希映射(HashMap)和哈希集(HashSet)实现,特点是它们能保留元素的插入顺序。这对于需要同时保持键值对排序和高效查找的场景非常有用。在C++标准库中,`std::map`和`...

    Notes on Partially Ordered Monoids

    在偏序幺半群的上下文中,正锥通常用M+表示,它具有以下性质:对于M+中的任意元素a, b和c,如果a ≤ b + c,那么存在正元x和y,使得a = x + y且x ≤ b,y ≤ c。这与线性空间中的正锥定义类似,但扩展到了非交换结构...

Global site tag (gtag.js) - Google Analytics