Java 搜索动物类的动物方法
我有一个方法,但我不太确定它的作用。我有一个动物类和一个动物列表。我正在努力理解它,这样我最终可以在将来使用类似的东西。有人能确切地解释一下它的作用吗 这是我的代码:Java 搜索动物类的动物方法,java,oop,Java,Oop,我有一个方法,但我不太确定它的作用。我有一个动物类和一个动物列表。我正在努力理解它,这样我最终可以在将来使用类似的东西。有人能确切地解释一下它的作用吗 这是我的代码: public Animal search(String name) { Animal result = null; for (Animal a : animals) { if (name.equals(a.getName())) { result = a;
public Animal search(String name) {
Animal result = null;
for (Animal a : animals) {
if (name.equals(a.getName())) {
result = a;
}
}
return result;
}
逐行:
public Animal search(String name) { //Method definition, parameter named name
Animal result = null; //Variable declaration to hold the result
for (Animal a : animals) { //for each loop, looping on all the animals and the current animal is stored in variable named a
if (name.equals(a.getName())) { //check if current animal's name is equal to parameter's value
result = a; //Yes, store it in result variable
}
}
return result; //In the end return result, it could be null if no animal is found
}
逐行:
public Animal search(String name) { //Method definition, parameter named name
Animal result = null; //Variable declaration to hold the result
for (Animal a : animals) { //for each loop, looping on all the animals and the current animal is stored in variable named a
if (name.equals(a.getName())) { //check if current animal's name is equal to parameter's value
result = a; //Yes, store it in result variable
}
}
return result; //In the end return result, it could be null if no animal is found
}
它看起来像一个函数,通过比较其
getName()
方法的值与传递给函数的字符串参数name
来搜索Animal
等数组中的Animal
实例
该函数查看
animals
中的所有元素,返回最后一个匹配项,即使可能已经找到了一个。它看起来像一个函数,通过比较getName()的值,在Animal
数组中搜索Animal
实例
方法,并将字符串参数name
传递给函数
函数查看
动物中的所有元素,返回最后一个匹配项,即使可能已经找到了一个。这是一种搜索方法,将搜索动物数组列表中的任何动物。假设您通过了“Dog”,那么它将在arraylist中检查任何名为“Dog”的动物
此动物对象将存储搜索结果。如果在arrayList中找到,则为Animal对象,否则为null
Animal result = null;
此for循环用于迭代动物数组列表中的所有动物
for (Animal a : animals) {
}
如果动物名称输入的名称与正在迭代的当前动物的名称相同,这将检查每个动物的名称。如果If
条件为true,则将其存储在result
对象中
if (name.equals(a.getName())) {
result = a;
}
这是一种搜索方法,可以搜索动物列表中的任何动物。假设您通过了“Dog”,那么它将在arraylist中检查任何名为“Dog”的动物
此动物对象将存储搜索结果。如果在arrayList中找到,则为Animal对象,否则为null
Animal result = null;
此for循环用于迭代动物数组列表中的所有动物
for (Animal a : animals) {
}
如果动物名称输入的名称与正在迭代的当前动物的名称相同,这将检查每个动物的名称。如果If
条件为true,则将其存储在result
对象中
if (name.equals(a.getName())) {
result = a;
}
公共动物搜索(字符串名称){
}公共动物搜索(字符串名称){
}这似乎是非常基本的代码,有什么不清楚的?顺便说一句:如果你指定了编程语言,这会有所帮助。很多人在没有已知语言标签的情况下不会阅读问题。这似乎是非常基本的代码,有什么不清楚的?顺便说一句:如果你指定了编程语言,这会有所帮助,很多人在没有已知语言标签的情况下不会阅读问题。