Java 与'有关的问题;等于';和';包含';功能
为什么此函数总是返回Java 与'有关的问题;等于';和';包含';功能,java,equals,contains,Java,Equals,Contains,为什么此函数总是返回false?例如,如果p.getId()=1和productTypes=[1,2,3],它应该返回true,但不会返回true productTypes _id = [1, 2, 3] p.getId() _id = 1 List productTypes=new ArrayList(); 布尔结果=productTypes.contains(p.getId()); 公共类ProductType { 私人内部id; 私有字符串\u名称; 公共产品类型(int-id)
false
?例如,如果p.getId()=1
和productTypes=[1,2,3]
,它应该返回true,但不会返回true
productTypes
_id = [1, 2, 3]
p.getId()
_id = 1
List productTypes=new ArrayList();
布尔结果=productTypes.contains(p.getId());
公共类ProductType
{
私人内部id;
私有字符串\u名称;
公共产品类型(int-id)
{
这个。_id=id;
}
公共产品类型(int-id,字符串名称)
{
这个。_id=id;
这个。_name=name;
}
公共int getId()
{
返回_id;
}
公共void setId(int\u id)
{
这个。_id=_id;
}
公共字符串getName()
{
返回_name;
}
public void setName(字符串_name)
{
这个。_name=_name;
}
@凌驾
公共布尔等于(对象obj){
if(obj==null){
返回false;
}
如果(getClass()!=obj.getClass()){
返回false;
}
最终产品类型其他=(产品类型)obj;
如果(此._id!=其他._id)
返回false;
返回true;
}
}
,因为您正在检查它是否包含id
,该id将自动装箱到整数
:
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;
}
}
您应该改为发送ProductType
:
productTypes.contains(p.getId()));
因为您正在检查它是否包含
id
,该id将自动装箱到整数
:
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;
}
}
您应该改为发送ProductType
:
productTypes.contains(p.getId()));
您的列表包含
ProductType
而不是整数。
i、 e.这将有助于:
productTypes.contains(新的ProductType(1))代码>您的列表包含ProductType
而不是整数。
i、 e.这将有助于:
productTypes.contains(新的ProductType(1))我不知道为什么,但是productTypes.contains(p);不起作用。@KlausosKlausos你确定p
是ProductType p
,对吗?我不知道为什么,但是productTypes.contains(p);不起作用。@克劳斯克劳斯你确定p
是ProductType p
,对吗?