同样hashCode的对象,为什么无法在HashMap中取出?

oneonone 2005-05-02 12:28:35
//一个对象被放进了HashSet, 当使用HashSet.contains(Object o)方法时,如果被传入的o 拥有与HashSet中已有对象相同的HashCode,那么这个方法会返回true,但实际上好像不是这么回事.

//如下的这个程序自己实现了一个复数(Complex)类,OverRide了其中的hashCode()方法.
//对于 相同的复数(Complex1.x == Complex2.x && Complex1.y == Complex2.y) hashCode方法肯定对返回相同的hash值


package com.dcs.unicom.debug;

import java.util.HashSet;

public class DebugClass {


public static void main(String[] args) {
HashSet hm = new HashSet();
//首先new 了一个Complex对象
Complex test = new Complex(1, 1);
//将这个对象放入了HashSet
hm.add(test);
System.out.println(test.hashCode());
//用contains方法判断一个相等的复数是否已经被放进了 HashSet中.
System.out.println(hm.contains(new Complex(1, 1)));
System.out.println(hm.contains(test));
}
}

class Complex {
private static final int BYTE_MAX = 256;
private int x = 0, y = 0;
public Complex(int x, int y) {
this.x = x >= 0 ? x : x + BYTE_MAX;
this.y = y >= 0 ? y : y + BYTE_MAX;
}

public synchronized int hashCode() {
return x + y * BYTE_MAX;
}

public String toString() {
return "" + x + " + i" + y;
}

public boolean equals(Complex c) {
return c.x == this.x && c.y == this.y;
}
}


//程序(contains(Object o))执行输出总是为false
//不知道这是什么原因,还望高手解答. (100分)
...全文
102 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
vgvg 2005-05-02
  • 打赏
  • 举报
回复
问题出在此:

public boolean equals(Complex c) {
return c.x == this.x && c.y == this.y;
}

你没有覆盖掉,应该改为
public boolean equals(Object c) {
return ((Complex)c).x == this.x && ((Complex)c).y == this.y;
}
oneonone 2005-05-02
  • 打赏
  • 举报
回复
谢谢!~
看来我的基础还真差得远

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧