HashSet行为令人惊讶

san*_*ane 0 java android hashset

我搜索了这个stackoverflow,发现了这种情况的无关线程.我也尝试了自己,并将继续尝试,直到解决方案.但如果有人告诉我,如果我在代码中犯了任何错误,那将会很好.


我有一个HashSet这样我可以防止重复的字符串被添加到它.如果HashSet是添加,那么它必须是唯一的字符串.


我的班级声明是:

public List<String> ContactsList;
public List<String> ContactsNumbersList;
Run Code Online (Sandbox Code Playgroud)

我的代码通过获取帮助来获取联系人并将其添加到这两个列表中,HashSet以便我保留重复的数字:

    ContactsList = new ArrayList<String>();
    ContactsNumbersList = new ArrayList<String>();

    HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();

    // Contacts Database queries

    Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null,  ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY +" ASC");


    while (cursor.moveToNext())
    {
        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        if (normalizedNumbersAlreadyFound.add(phoneNumber))
        {
            phoneNumber = phoneNumber.replace("-","");
            phoneNumber = phoneNumber.replace(" ","");
            phoneNumber = phoneNumber.replace("(","");
            phoneNumber = phoneNumber.replace(")","");
            ContactsList.add(name);
            ContactsNumbersList.add(phoneNumber);
        }

    }
    cursor.close();
Run Code Online (Sandbox Code Playgroud)

那么为什么我ContactsNumbersList有重复的条目...?提前感谢您的任何建议..这将有助于我.

Men*_*ena 9

你的设计似乎有问题.

首先,List如果您的目标是使用没有重复的集合,则不需要s.

只需使用你的Set.

其次,特别是对于您的代码,您正在检查元素是否已添加到您的标准化Set 之前,并将标准化添加StringList.

因此,很可能您的List遗嘱将包含重复项,因为在归一化之前,两个在归一化之前不同的元素可能相等.

这让我回过头来建议你Set直接使用你,并List在这个用例中使用a .

List<String> source = Arrays.asList("123-456789", "(1)23456789");
System.out.printf("Source List contains: %s%n", source);
Set<String> set = new HashSet<>();
List<String> unnecessary = new ArrayList<>();
Set<String> useful = new HashSet<>();

for (String s: source) {
    if (set.add(s)) System.out.printf("Added %s to set.%n", s);
    s = s.replaceAll("[()-]", "");
    System.out.printf("\t... now normalized to %s%n", s);
    // s is now normalized
    unnecessary.add(s);
    useful.add(s);
}
System.out.printf(
    "Set contains %s.%nUnnecessary List contains %s.%nUseful Set contains %s.%n", 
    set, 
    unnecessary,
    useful
);
Run Code Online (Sandbox Code Playgroud)

产量

Source List contains: [123-456789, (1)23456789]
Added 123-456789 to set.
    ... now normalized to 123456789
Added (1)23456789 to set.
    ... now normalized to 123456789
Set contains [(1)23456789, 123-456789].
Unnecessary List contains [123456789, 123456789].
Useful Set contains [123456789].
Run Code Online (Sandbox Code Playgroud)