【问题标题】:Error in removing duplicates in ArrayList [closed]删除 ArrayList 中的重复项时出错 [关闭]
【发布时间】:2014-03-04 18:56:58
【问题描述】:

我遇到了这段代码的问题 - 它不应该添加重复的字符串,以防遇到一些。我不明白它为什么会崩溃。

Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
Temp = people.getString(NameIndex);
myArr.add(Temp.toString());

while (people.moveToNext()) {
    NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);    
    Name = people.getString(NameIndex);

    if((Name.toString()).equals(Temp)) {
    }
    else {
        myArr.add(Name.toString());
        Temp = Name.toString();
    }
}

【问题讨论】:

  • 我没有找到从数组列表中删除元素的代码
  • 它在哪里崩溃?你有一些 LogCat 输出要分享吗?
  • 我们知道的比你还少,因为你没有提供任何细节或堆栈跟踪。此外,您没有遵循 Java 编码标准。

标签: java android android-listview arraylist


【解决方案1】:

您可以使用 ArrayList 的内置函数来检查字符串是否已经存在。此外,如果该列不存在,getColumnIndex() 将返回 -1,如果发生这种情况,则不能在 getString() 的下一行中使用它。您需要的修改很少:

  • 检查 getColumnIndex() 是否找到您要查找的列
  • 使用ArrayList的内置方法检查String是否已经存在

修改代码:

while (people.moveToNext()) {
    NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);

    //check if we have a valid column index
    if (NameIndex != -1) {
        Name = people.getString(NameIndex);

        if(myArr.contains(Name)) {
            // do nothing, as the same String is already in the list
        }
        else {
            myArr.add(Name.toString());
        }
    }    
}

注意:Java 约定以小写开头的变量名。

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 2018-05-29
    • 2015-12-12
    • 1970-01-01
    • 2011-01-26
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多