How do define my own element class for use with Set

前端 未结 2 1064
悲&欢浪女
悲&欢浪女 2021-01-13 06:31

I have the following code:

public class MyElement {
    String name;
    String type;

    MyElement(String name, String type) {
        this.name = name;
           


        
相关标签:
2条回答
  • 2021-01-13 06:52

    You need to implement equals(Object o) and hashCode() on MyElement per the general contract. Absent that Set.contains() will use the default implementation which compares the memory address of the objects. Since you're creating a new instance of MyElement in the contains call it comes back as false.

    0 讨论(0)
  • 2021-01-13 07:13

    You should override an equals(MyElement me) function. Equals returns a boolean

    Otherwise, you are checking that two items are the same instance of an object, not that their internal content is the same.

    MyElement(String name, String type) {
        this.name = name;
        this.type = type;
    }
    
    public boolean Equals<MyElement>(MyElement me) {
        return this.name.equals(me.name) && this.type.equals(me.type);
    }
    
    0 讨论(0)
提交回复
热议问题