我目前正在研究以下问题:
Assume a class Name has attributes "surname" and "firstname" stored as Strings. Let "regist" be a list of Name with declaration:
ArrayList<Name> regist = new ArrayList<Name>();
Assuming that "regist" is populated, implement the method below that finds a name in the list with the given surname, or returns null if no matching name exists in the list. (You may write Java code or a mix of Java and pseudo-code).
public Name find(String surname) { //... to do ... }
到目前为止我能够得到的答案是:
public Name find (String surname)
{
this.surname = surname;
return null;
}
public Name()
{
surname = " ";
}
之后,我就被困在这里了,如果有人能告诉我如何完成这段代码,那么我将非常感谢您的帮助,提前致谢。
(如果我能够正确完成此代码,我将能够正确测试该代码)。
最佳答案
您必须循环遍历 regList
中的项目并返回具有给定姓氏的 Name
对象。您当前的 find 代码不正确 - find 方法不在 name 类中,并且(或不应)被允许直接更改 Name
对象内的变量。
无论如何,解决方案是:
public Name find(String surname)
{
for(Name obj : regList)
{
// Check the object's surname with the given one
// Should check if obj is null
// Must use .equals to compare strings.
if(obj.surname.equals(surname))
return obj;
}
// Not found
return null;
}
关于java - 如何使用 ArrayList 在寄存器中查找名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376584/