简体   繁体   English

indexOf() 在 java 中使用 ArrayList

[英]indexOf() using ArrayList in java

I've a class A which is as follows:我有一个A类,如下所示:

A{
     String name;
     ArrayList<Bike> firstArray;
     ArrayList<Cycle> secondArray;
     // it's constructors and related methods are down lines.
 }

and I have two instances of it named a_Obj and b_obj .我有两个名为a_Objb_obj实例。 I compare only the variable , name inside object a_Obj with b_Obj using indexOf .我使用indexOf仅比较对象a_Objb_Obj的变量name

My question is how to call indexOf in this case and in other words how to tell the compiler that I just want to compare name of two objects regardless of ArrayLists declared inside the class A .我的问题是在这种情况下如何调用indexOf ,换句话说,如何告诉编译器我只想比较两个对象的name ,而不管类A声明的 ArrayLists 是什么。

你可以在你的班级中覆盖 equals()

Given below is how indexOf has been implemented by default:下面给出了默认情况下indexOf实现方式:

public int indexOf(Object o) {
    ListIterator<E> it = listIterator();
    if (o==null) {
        while (it.hasNext())
            if (it.next()==null)
                return it.previousIndex();
    } else {
        while (it.hasNext())
            if (o.equals(it.next()))
                return it.previousIndex();
    }
    return -1;
}

By overriding the equals method in A to consider just the equality of name , you can make it happen.通过覆盖Aequals方法以仅考虑name的相等性,您可以实现它。

Given below is the definition generated by Eclipse IDE:下面给出的是 Eclipse IDE 生成的定义:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    A other = (A) obj;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
}

A shorter version for the same can be as follows:相同的较短版本如下:

@Override
public boolean equals(Object obj) {
    if (obj == null)
        return false;
    A other = (A) obj;
    return Objects.equals(name, other.name);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM