Java hashCode from one field

前端 未结 3 604
遥遥无期
遥遥无期 2021-01-05 14:32

Edit: Prepare my objects for the use within a HashMap.

after reading a bit about how to generate a hash code, im kind of confused now. My (probably trivial) question

3条回答
  •  攒了一身酷
    2021-01-05 14:44

    If you want objects with different ids to identified by that id all you need to do is return it/compare it.

    private final int id;
    
    public int hashCode() { return id; }
    
    public boolean equals(Object o) { 
        return o instanceof ThisClass && id == ((ThisClass)o).id;
    }
    

提交回复
热议问题