java - 在 Java 中使用 indexOf() 查找对象 arrayList 的索引值

标签 java arrays oop indexof compareobject

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某种类型(例如 staffArrayList<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/

相关文章:

javascript - 如何在数组中查找所有具有假值的对象?

javascript - 扩展 Web API 类构造函数

Java:网络设置窗口

java - 如何模拟 Spring ConversionService?

arrays - 如何在 MATLAB 中遍历 n 维矩阵中的每个元素?

javascript - JavaScript 问题中的中介模式

javascript - JavaScript 中的 Java 式 OOP 和 jQuery 失败

java - 强制先执行 "WebFilter"

java - WAS Liberty 8.5.5.7 是否支持邮件资源配置?

c - 如何区分动态分配的 char* 和静态 char*