简体   繁体   English

列表/哈希集中使用的自定义类

[英]Custom Class Used in A List/HashSet

I have a custom class that looks like below: 我有一个自定义类,如下所示:

public class customClass(){
    private int keyCode;
    private boolean up;
    private String toTrigger;

    public String getTrigger();
    public boolean up();
    public int keyCode();
}

Whats the best way for performance to have a list of unique values? 拥有唯一值列表的最佳性能是什么?

I was thinking of a HashSet but how would i make sure its only unique instances of my customClass? 我当时在想一个HashSet,但是我如何确定它的customClass唯一实例呢?

What do i need to override? 我需要覆盖什么? Equals and HashCode? 等于和HashCode? will that make sure that my Hash Set of CustomClass only have unique instances? 可以确保我的CustomClass哈希集只有唯一的实例吗?

Thanks 谢谢

If a.equals(b) is true then there hashcode() must also be same. 如果a.equals(b)是真的,那么有hashCode()方法也必须是相同的。

  • Override both .equals() and .hashCode() in your custom class. 在您的自定义类中重写.equals()和.hashCode()。

    Use the same fields of your custom class to calculate hashCode which you used to check equality in .equals(). 使用自定义类的相同字段来计算用于检查.equals()中是否相等的hashCode。

  • Yes it'll make sure that there are only unique instances of your customClass in hash-set. 是的,它将确保哈希集中仅存在customClass的唯一实例。 So go for it. 所以去吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM