gpt4 book ai didi

java - HashMap 有 key,但它的 containsKey 方法返回 false?

转载 作者:太空宇宙 更新时间:2023-11-04 13:19:00 24 4
gpt4 key购买 nike

这是我的 map 条目的日志。存在两个相同的 key 。这怎么可能?

 Map<String, Objects> map = new HashMap<String, Objects>();

addContact("+917111111111");
addContact("+919222222222");
addContact("+919222222222");

private void addContact(String number){
if(TextUtils.isEmpty(number))return;

number = number.trim();
number = number.replaceAll("-", "");
number = number.replaceAll(" ", "");

if(!map.containsKey(number)) {
map.put(number, null);
}
}
/* While debugging in android studio. I have found the map have below entry.
0 = {HashMap$HashMapEntry@3798} "+919222222222" -> "null"
1 = {HashMap$HashMapEntry@3832} "‪+919222222222" -> "null"
2 = {HashMap$HashMapEntry@3694} "+917111111111" -> "null"
*/
map.containsKey("+919222222222");// ==> return false

为什么会发生这种情况?

实际任务:

private void getContacts(){
try {
Cursor cursor = null;
StringBuffer sb = new StringBuffer();

Map<String, Object> map = new HashMap<String, Object>();
try {
String strOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, strOrder);
int contactIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
//...
phoneNumber = getFormatedNumber(phoneNumber);

//as map key same phone number can not be two times
if(!map.containsKey(phoneNumber)) {
map.put(phoneNumber, null);
sb.append("\nPhone Number:--- " + phoneNumber + "\nUser Name:--- "
+ name);
sb.append("\n----------------------------------");
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
textView.setText(sb); //As in output it shows one number showing two times
} catch (Exception e) {
e.printStackTrace();
}
}

private String getFormatedNumber(String number){
if(TextUtils.isEmpty(number))return null;

number = number.trim();
number = number.replaceAll("-", "");
number = number.replaceAll(" ", "");

return number;
}

最佳答案

经过所有讨论,我发现出现这样的问题是由于我的字符串中附加了 unicode 字符,该字符在调试时不可见,但如果我们复制到记事本中,则它清晰可见。就像:'\u202A\u202A+91922222222\u202A\u202C'

关于java - HashMap 有 key,但它的 containsKey 方法返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33278452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com