gpt4 book ai didi

java - ArrayList 包含方法无法正常工作?

转载 作者:行者123 更新时间:2023-11-29 09:33:22 25 4
gpt4 key购买 nike

<分区>

ArrayList 在其 contains 方法中使用 equals() 来查看提供的对象是否等于列表中的任何项目,如文档所述:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). see this

我有这门课

class Foo
{
private String value;
public Foo(String value)
{
this.value = value;
}

@Override
public boolean equals(Object o)
{
return o == null ? this.value == null : o.toString().equals(this.value);
}
}

我想使用 contains 方法来检查项目是否存在这样的

List<Foo> list = new ArrayList<Foo>();

Foo item1 = new Foo("item1");
Foo item2 = new Foo("item2");
list.add(item1);
list.add(item2);

System.out.println(item1.equals("item1")); //return true
System.out.println(list.contains("item1")); //false !! why?!

contains 方法返回 false ,而 item1.equals("item1") 返回 true

为什么 contains 在对提供的对象使用 equals 方法时返回 false

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com