【问题标题】:indexOf() using ArrayList in javaindexOf() 在 java 中使用 ArrayList
【发布时间】:2020-03-01 18:53:07
【问题描述】:

我有一个班级A,内容如下:

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

我有两个名为 a_Objb_obj 的实例。我使用indexOf 仅将对象a_Obj 内部的变量nameb_Obj 进行比较。

我的问题是在这种情况下如何调用indexOf,换句话说,如何告诉编译器我只想比较两个对象的name,而不考虑在A 类中声明的ArrayLists。

【问题讨论】:

    标签: java arraylist collections indexof


    【解决方案1】:

    你可以在你的类中重写 equals()

    【讨论】:

      【解决方案2】:

      下面给出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;
      }
      

      通过覆盖A 中的equals 方法以仅考虑name 的相等性,您可以实现它。

      下面给出的是 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;
      }
      

      相同的较短版本如下:

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

      【讨论】:

      • return name.equals(other.name);
      • @WJS - 我不赞成您建议的解决方案,因为当namenull 时,它会抛出NullPointerException
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多