HashMap如何实现Map接口,确保键值对唯一映射?

更新于
2026-10-12 10:33:10
2阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计311个文字,预计阅读时间需要2分钟。

HashMap如何实现Map接口,确保键值对唯一映射?

HashMap基于HashCode,在所有对象超类Object中有一个hashCode()方法,但与equals()方法一样,并不能适用于所有情况。因此,我们需要重写自己的hashCode()方法。以下是一个示例:

javapublic class CustomObject { private int key; private String value;

HashMap如何实现Map接口,确保键值对唯一映射?

public CustomObject(int key, String value) { this.key=key; this.value=value; }

@Override public int hashCode() { return Integer.hashCode(key); }

// 省略equals和其他方法}

HashMap是基于HashCode的,在所有对象的超类Object中有一个HashCode()方法,但是它和equals方法一样,并不能适用于所有的情况,这样我们就需要重写自己的HashCode()方法。下面就举这样一个例子:

import java.util.*; public class Exp2 { public static void main(String[] args) { HashMap h2 = new HashMap(); for (int i = 0; i < 10; i++) { h2.put(new Element(i), new Figureout()); System.out.println("h2:"); System.out.println("Get the result for Element:"); } Element test = new Element(3); if (h2.containsKey(test)) {System.out.println((Figureout) h2.get(test));} else { System.out.println("Not found"); } class Element { int number; public Element(int n) { number = n; } class Figureout { Random r = new Random(); boolean possible = r.nextDouble() > 0.5; public String toString() { if (possible) { return "OK!"; } else { return "Impossible!"; } } 如果你想有效的使用HashMap,你就必须重写在其的HashCode()。

class Element { int number; public Element(int n) { number = n; } public int hashCode() { return number; } public boolean equals(Object o) { return (o instanceof Element) && (number == ((Element) o).number); } }

本文共计311个文字,预计阅读时间需要2分钟。

HashMap如何实现Map接口,确保键值对唯一映射?

HashMap基于HashCode,在所有对象超类Object中有一个hashCode()方法,但与equals()方法一样,并不能适用于所有情况。因此,我们需要重写自己的hashCode()方法。以下是一个示例:

javapublic class CustomObject { private int key; private String value;

HashMap如何实现Map接口,确保键值对唯一映射?

public CustomObject(int key, String value) { this.key=key; this.value=value; }

@Override public int hashCode() { return Integer.hashCode(key); }

// 省略equals和其他方法}

HashMap是基于HashCode的,在所有对象的超类Object中有一个HashCode()方法,但是它和equals方法一样,并不能适用于所有的情况,这样我们就需要重写自己的HashCode()方法。下面就举这样一个例子:

import java.util.*; public class Exp2 { public static void main(String[] args) { HashMap h2 = new HashMap(); for (int i = 0; i < 10; i++) { h2.put(new Element(i), new Figureout()); System.out.println("h2:"); System.out.println("Get the result for Element:"); } Element test = new Element(3); if (h2.containsKey(test)) {System.out.println((Figureout) h2.get(test));} else { System.out.println("Not found"); } class Element { int number; public Element(int n) { number = n; } class Figureout { Random r = new Random(); boolean possible = r.nextDouble() > 0.5; public String toString() { if (possible) { return "OK!"; } else { return "Impossible!"; } } 如果你想有效的使用HashMap,你就必须重写在其的HashCode()。

class Element { int number; public Element(int n) { number = n; } public int hashCode() { return number; } public boolean equals(Object o) { return (o instanceof Element) && (number == ((Element) o).number); } }