如何实现Java Hashtable的自定义键

   2024-09-30 2960
核心提示:在Java中,要实现一个自定义键(key)来用于Hashtable,需要遵循以下步骤:创建一个类,该类将作为Hashtable的键。在这个类中,

在Java中,要实现一个自定义键(key)来用于Hashtable,需要遵循以下步骤:

创建一个类,该类将作为Hashtable的键。在这个类中,覆盖equals()hashCode()方法。这两个方法对于Hashtable的键来说非常重要,因为它们用于确定两个键是否相等以及为键生成一个唯一的哈希值。如果需要,可以覆盖toString()方法,以便更好地表示键的内容。

下面是一个简单的例子,展示了如何实现一个自定义键:

import java.util.Hashtable;public class CustomKey {    private int id;    private String name;    public CustomKey(int id, String name) {        this.id = id;        this.name = name;    }    @Override    public boolean equals(Object obj) {        if (this == obj) {            return true;        }        if (obj == null || getClass() != obj.getClass()) {            return false;        }        CustomKey other = (CustomKey) obj;        return id == other.id && (name == null ? other.name == null : name.equals(other.name));    }    @Override    public int hashCode() {        int result = 17;        result = 31 * result + id;        result = 31 * result + (name == null ? 0 : name.hashCode());        return result;    }    @Override    public String toString() {        return "CustomKey [id=" + id + ", name=" + name + "]";    }    public static void main(String[] args) {        Hashtable<CustomKey, String> hashtable = new Hashtable<>();        CustomKey key1 = new CustomKey(1, "Alice");        CustomKey key2 = new CustomKey(2, "Bob");        hashtable.put(key1, "Value for Alice");        hashtable.put(key2, "Value for Bob");        System.out.println("Value for key1: " + hashtable.get(key1));        System.out.println("Value for key2: " + hashtable.get(key2));    }}

在这个例子中,我们创建了一个名为CustomKey的类,它包含两个属性:idname。我们覆盖了equals()hashCode()方法,以便Hashtable可以正确地处理这些键。然后,我们在main()方法中创建了一个Hashtable,并使用CustomKey作为键来存储和检索值。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号