本文介绍了如何返回ArrayList& lt; Field& gt;的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检索列表中特定元素的索引:

I want to retrive index of specific element of my list :

    ArrayList<Field> list = new ArrayList<Field>();
    list.addAll(profile.getFieldsList());

    Object privacyName = "privacy";
    int i = list.indexOf(privacyName);
    boolean doesContain = list.contains(privacyName);

列表中有一个包含"privacy"的字段,但我始终为-1,而dosContain始终为false.为什么此搜索无效?

There is a field containing "privacy" in the list but i is always -1 and doesContain is always false. Why this search doesn't work ?

推荐答案

    public int indexOf(Object o) {
         if (o == null) {
             for (int i = 0; i < size; i++)
                 if (elementData[i]==null)
                     return i;
         } else {
             for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
   }

您需要重写equals以获得逻辑相等性,或者依赖default来获得引用相等性.

You need to override equals for logical equality or rely on default for reference equality.

在这种情况下, privacyName.equals(elementData [i])始终为假.

In this case privacyName.equals(elementData[i]) is always false.

这篇关于如何返回ArrayList&amp; lt; Field&amp; gt;的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:07