'equals'和'contains'函数问题

时间:2014-05-07 16:11:36

标签: java equals contains

productTypes 
 _id = [1, 2, 3]

p.getId()
 _id = 1

为什么此函数始终返回false?例如,如果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;
    }

}

2 个答案:

答案 0 :(得分:3)

因为您要检查它是否包含id,其中Integer会自动退回到productTypes.contains(p.getId()));

ProductType

您应该发送productTypes.contains(p); 代替:

{{1}}

答案 1 :(得分:0)

您的列表包含ProductType而不是整数。 即这将工作: productTypes.contains( new ProductType( 1 ) );