[英]What parameters should I use for the contains() method?
I don't really understand what parameters I should pass to the contains() method. 我不太了解应将哪些参数传递给contains()方法。 I have my own class called Name which consists of 2 strings (firstName, secondName).
我有自己的名为Name的类,该类由2个字符串(firstName,secondName)组成。 I have created an ArrayList of type Name and 2 Name objects of the same name eg ("Joe, "Bloggs") 2x. So what paremeters do I have to pass to check whether it works. I have correctly overriden the equals method for Name class. This is my main program:
我创建了一个Name类型和2个Name对象的ArrayList,这些对象具有相同的名称,例如(“ Joe,” Bloggs“)2x。因此,我必须通过哪些参数来检查其是否有效,我已经正确地覆盖了Name的equals方法类,这是我的主要程序:
import java.util.ArrayList;
public class EqualsTest {
public static void main(String[] args) {
ArrayList<Name> names = new ArrayList<Name>();
names.add(new Name("Joe", "Bloggs"));
names.add(new Name("John", "Smith")); //<--
names.add(new Name("Alan", "Wake")); // | the same name
names.add(new Name("Robert", "High"));// |
names.add(new Name("John", "Smith")); //---
names.contains(Name("Joe", "Bloggs"));
}
}
Assuming you've overridden equals
correctly in your Name
class, it should be: 假设您在
Name
类中正确覆盖了equals
,则应为:
if (names.contains(new Name("Joe", "Bloggs"))) {
...
}
You can use 您可以使用
names.contains(new Name("Joe", "Bloggs"));
But you should override equals()
method in Name class to work it as expected. 但是您应该重写Name类中的
equals()
方法以按预期工作。
When ever you need to deal with collection frame work in Java
, better to override both equals()
and hashCode()
method in your classes else you end up with mess. 每当您需要处理
Java
集合框架工作时,最好在类中同时覆盖equals()
和hashCode()
方法,否则最终会陷入混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.