简体   繁体   English

具有“等于”和“包含”功能的问题

[英]Issue with 'equals' and 'contains' functions

productTypes 
 _id = [1, 2, 3]

p.getId()
 _id = 1

Why does this function always return false ? 为什么此函数总是返回false For instance, if p.getId() = 1 and productTypes = [1, 2, 3] , it should return true, but it doesn't. 例如,如果p.getId() = 1productTypes = [1, 2, 3] ,则应返回true,但不是。

List<ProductType> productTypes = new ArrayList<ProductType>();

boolean result = productTypes.contains(p.getId()));


public class ProductType 
{

    private int _id;
    private String _name;

    public ProductType(int id)
    {
        this._id = id;
    }

    public ProductType(int id,String name)
    {
        this._id = id;
        this._name = name;
    }

    public int getId() 
    {
        return _id;
    }

    public void setId(int _id) 
    {
        this._id = _id;
    }

    public String getName() 
    {
        return _name;
    }

    public void setName(String _name) 
    {
        this._name = _name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final ProductType other = (ProductType) obj;
        if (this._id != other._id)
            return false;
        return true;
    }

}

Because you're checking if it contains the id , which will be autoboxed to Integer : 因为您正在检查它是否包含id ,它将被自动装箱到Integer

productTypes.contains(p.getId()));

You should send the ProductType instead: 您应该改为发送ProductType

productTypes.contains(p);

Your list contains ProductType not integers. 您的列表包含ProductType而不是整数。 ie This would work: productTypes.contains( new ProductType( 1 ) ); 即,这将工作: productTypes.contains( new ProductType( 1 ) );

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

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