【问题标题】:How to get the Index of an element from an array using Arrays.asList如何使用 Arrays.asList 从数组中获取元素的索引
【发布时间】:2016-08-19 13:40:16
【问题描述】:

我在 android 中有一个这样的数组,Arrays.asList 的用法是不同的,因为我用不同的类“Person”制作了数组:

 people = new Person[]{
            new Person("Python"),
            new Person("PHP"),
            new Person("Pascol"),
            new Person("PyCrust"),
            new Person("C"),
            new Person("C#"),
            new Person("C++")

    };

我以这种方式使用 Arrays.asList

 int index= Arrays.asList(people).indexOf("Pascol");
    String tags = Integer.toString(index);
    Toast.makeText(getApplication(),tags,Toast.LENGTH_SHORT).show();

但是我在吐司中得到了“-1”的值。 我找不到故障。

【问题讨论】:

  • int index= Arrays.asList(people).indexOf(new Person("Pascol"));
  • 您需要在 Person 类中重写 equals() 和 hashcode() 并使用“pascol”而不是字符串来发送 Person 对象。
  • @Nambari 是的,我们都是对的 :)

标签: android arrays


【解决方案1】:

问题是您有一个Person 对象列表。当你调用.indexOf("Pascol"); 时,你传入了String。比较 PersonString 将始终返回 false。请改为这样做

int index = -1;
for (int i = 0; i < people.length; i++) {
    if (people[i].getName().equals("Pascol")) {
        index = i;
    }
}

String tags = Integer.toString(index);
    Toast.makeText(getApplication(),tags,Toast.LENGTH_SHORT).show();

【讨论】:

    【解决方案2】:
    int index = Arrays.asList(people).indexOf("Pascol");
    

    Pascol 在这里是String,但数组中的对象是Person 类型的对象。所以indexOf 方法不能将StringPerson 匹配。您需要覆盖equals()hashcode() 并将Person 类型参数传递给名称为PascolindexOf。当然,我假设您的对象的相等性仅取决于 name 属性。

    【讨论】:

      【解决方案3】:

      你应该在 Person 类中实现 Comparable

      【讨论】:

        猜你喜欢
        • 2022-01-12
        • 1970-01-01
        • 2011-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多