java 对象重复,Java:添加到集合中的重复对象?

这篇博客探讨了在Java中,当两个对象根据hashCode()和equals()方法判断相等时,HashSet为何仍会认为它们是不同元素的问题。错误在于没有正确重写hashCode()方法。解决方案是使用@Override注解确保重写,并确保equals()和hashCode()方法遵循一致性的约定。此外,还强调了代码格式化的重要性。
摘要由CSDN通过智能技术生成

If I run the below code then the output is 2 which means that the set contains 2 elements. However I think that set should contain 1 since both the objects are equal based on hashcode() value as well as .equals() method.

Seems like some obvious mistake in my understanding ?

package HELLO;

import java.util.HashSet;

import java.util.Set;

public class Test {

public static void main(String[] args) throws Exception {

Set s = new HashSet();

Alpha a1 = new Alpha();

Alpha a2 = new Alpha();

s.add(a1);

s.add(a2);

System.out.println(s.size());

}

}

class Alpha {

int a = 10;

public int hashcode() {

return a;

}

public boolean equals(Object obj) {

return (obj instanceof Alpha && ((Alpha) obj).a == this.a);

}

public String toString() {

return "Alpha : " + a;

}

}

解决方案

Your hashcode method does not override the Object class's hashCode method and thus your equals method breaks contract since it doesn't agree with the hashCode results, and you can have objects that are "equal" but have different hashCodes.

Remember: You should always use the @Override annotation when overriding methods as this will help you catch this and similar errors.

@Override // ** don't forget this annotation

public int hashCode() { // *** note capitalization of the "C"

return a;

}

Also, you will want to improve your code formatting, especially when posting code here for our review. We will be able to better understand your code and help you if it conforms to standards (that's why standards exist). So try to keep your indentations consistent with all code lines that are in the same block indented at the same level, and you will want to be sure that base level code, including imports, outer class declarations and its end curly brace, is flush left:

import java.util.HashSet;

import java.util.Set;

public class Test {

public static void main(String[] args) throws Exception {

Set s = new HashSet();

Alpha a1 = new Alpha();

Alpha a2 = new Alpha();

s.add(a1);

s.add(a2);

System.out.println(s.size());

}

}

class Alpha {

int a = 10;

@Override

public int hashCode() {

return a;

}

public String toString() {

return "Alpha : " + a;

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

Alpha other = (Alpha) obj;

if (a != other.a)

return false;

return true;

}

}

For a beautiful review on this, please read: Overriding equals and hashCode in Java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值