This method scans the current staff Employee array to see whether there is a match between the any member of staff and the Employee passed in.
Return -1 if there is no match, and the index number of the Employee if there is a match.
现在我的问题是,我该如何使用 -
indexOf();
正确获取对象的索引值,进而获取其 empId 与传入员工匹配的员工
public int findEmployee(Employee emp) {
int index = -1;
for (Employee s : staff) {
if (emp.getEmpId() == s.getEmpId()) {
index = indexOf(); //how to use this
}
}
return index;
}
我愿意接受任何其他比较方式,因为我知道indexOf()可以搜索并找到empId 对我来说。因此,如果我必须完全取消if 语句,我不介意。我认为这将使代码更加有效。
最佳答案
来自评论,因为 indexOf()
的解释评论可能会太长。其他回答者提供了很好的选择,但我会按照要求的方式回答。
我假设您正在使用 List
某种类型(例如 staff
是 ArrayList<Employee>
),如 Arrays
实用程序类似乎没有 indexOf()
方法。
不幸的是,我没有 C++ 经验,所以我不确定 Java 中的哪些概念可以很好地映射到 C++。如果您有任何疑问,请随时提问。
ArrayList#indexOf(Object o) 的 javadoc状态:
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that
(o==null ? get(i)==null : o.equals(get(i)))
, or -1 if there is no such index.
有趣的部分是:
returns the lowest index i such that
(o==null ? get(i)==null : o.equals(get(i)))
本质上,什么indexOf()
会做的是循环列表,直到找到一个元素:
- 如果
o == null
,该元素也为 null - 如果
o != null
,o.equals(element)
返回 true
或者如果不存在这样的元素,则 -1
将被退回。我假设您传入的员工非空,我将重点关注第二个选项。
o.equals(element)
是不言自明的。但是,有一点需要注意:如果 Employee
类不会覆盖 equals()
,您可能不会得到您想要的行为。这是因为 equals()
的默认实现检查引用相等性(其中您要比较的两个引用指向同一个底层对象,类似于我在 C++ 中猜测的两个指针指向同一位置/对象),而不是 < em>对象相等(“正常”等于,如果两个对象“代表同一事物”,则它们相等,即使它们是不同的对象)。
因此,在您的情况下,如果您想通过 ID 号匹配员工,则需要编写 equals()
接受一个对象的方法,检查它是否是 Employee
,如果是,则传递的对象的员工 ID 是否与您正在调用的员工的 ID 匹配 equals()
在。当然,如果有这样的equals()
方法已经存在,那么你不需要做任何事情。如果equals()
已经被覆盖并且有一些不同的行为,那么你可能会运气不好......
另外,请注意您使用的方法签名是 equals(Object o)
,并且不equals(Employee e)
。这是两个不同的方法签名,只有第一个会覆盖 Object#equals()
.
一旦你有了合适的equals()
编写的方法,indexOf()
应该为您完成其余的工作。
关于java - 在 Java 中使用 indexOf() 查找对象 arrayList 的索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23586063/