【问题标题】:Issue with 'equals' and 'contains' functions'equals' 和 'contains' 函数的问题
【发布时间】:2014-06-24 17:38:49
【问题描述】:
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;
    }

}

【问题讨论】:

    标签: java equals contains


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      因为您正在检查它是否包含id,它将被自动装箱为Integer

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

      您应该改为发送ProductType

      productTypes.contains(p);
      

      【讨论】:

      • 我不知道为什么,但是 productTypes.contains(p);不起作用。
      • @KlausosKlausos 你确定pProductType p,对吗?
      猜你喜欢
      • 2012-02-20
      • 2020-02-25
      • 2012-12-03
      • 1970-01-01
      • 2012-01-16
      • 2015-07-20
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      相关资源
      最近更新 更多