你好,我有一个对象数组,我希望能够有一个方法,通过类数组nameList查找特定的姓氏,然后返回与姓氏相匹配的实例,包括名字和lasttname。
Name[] nameList= new Name[] {
new Name("Mason","Akman"),
new Name("Ethan","Aldo"),
new Name("Pi","Manly"),
new Name("Shu","Hing"),
new Name("Mane","Dove"),
new Name("Minky","Maduno")}:
到目前为止,我的方法是
public Name lookup(String lastname) {
for (Name lookup : nameList) {
if (lookup.equals(lastname)) {
return nameList;
} else {
continue;
}
}
}
然而,这不会工作,因为我不能从Name[]转换为Name。似乎不知道我哪里出错了,希望得到帮助。
编辑:这里是name类
public class Name {
private String firstName;
private String lastName;
public Name(String firstName,String lastName) {
this.setFirstName(firstName);
this.setLastName(lastName);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return "First Name: "+this.firstName+
"Last Name: "+this.lastName;
}
}
你的代码有2个问题。
1)返回类型期望返回一个Name,即整个nameList2)该方法必须返回一些东西,所以在你的for循环之外,你需要添加一个返回语句,如果没有找到匹配的名字,可以返回一个默认的null。
public Name lookup(String lastname) {
for (Name lookup : nameList) {
if (lookup.getLastName().equals(lastName)) {
return lookup; //Changed this line to return lookup (a Name) instead of nameList
}
// else { //The else is unnecessary
// continue;
// }
}
return null; //Added this as a default return when no matching name was found
}
public Name lookup(String lastname)
. 它应该返回一个Name,而不是Name的数组。Object.equals()对所有实例都可用。但是,如果你想通过检查一个Name.Object.equals()来查找他们的 姓氏你应该对该属性进行equals()检查。
public Name lookup(String lastname) {
for (Name lookup : nameList) {
if (lookup.getLastName().equals(lastname)) { // check the input parameter against the lastName attribute of the Name object, not the Name itself
return lookup; // if a match is found, return the name and end this routine
} else { // unnecessary, but not an error. for-loop will push the iteration forward, you don't have to do it yourself
continue;
}
}
return null; // if this line is reached, means no matched is found, return a null
}
这可以通过java-8 Stream API轻松实现,只需创建一个流,对搜索的内容进行过滤。lastname
并返回第一个Name
实例,否则返回 否则返回 null
.
下面的代码应该可以工作,只要所提供的 lastname
不是 null
:
public Name lookup(String lastname){
return Arrays.stream(nameList)
.filter(n -> lastname.equals(n.getLastName()))
.findFirst()
.orElse(null);
}