相关疑难解决方法(0)

Java:为方便起见,在equals()中使用hashCode()?

考虑以下测试用例,将equals中的hashCode()方法用作方便的快捷方式是不好的做法?

public class Test 
{    
    public static void main(String[] args){
        Test t1 = new Test(1, 2.0, 3, new Integer(4));
        Test t2 = new Test(1, 2.0, 3, new Integer(4));
        System.out.println(t1.hashCode() + "\r\n"+t2.hashCode());
        System.out.println("t1.equals(t2) ? "+ t1.equals(t2));
    }

    private int myInt;
    private double myDouble;
    private long myLong;
    private Integer myIntObj;

    public Test(int i, double d, long l, Integer intObj ){
        this.myInt = i;
        this.myDouble = d;
        this.myLong = l;
        this.myIntObj = intObj;
    }

    @Override
    public boolean equals(Object other)
    {        
        if(other == null) …
Run Code Online (Sandbox Code Playgroud)

java equals hashcode

18
推荐指数
5
解决办法
4885
查看次数

标签 统计

equals ×1

hashcode ×1

java ×1