我有联系人被添加到数组列表中,现在一些联系人在其他应用程序中很常见,因此重复的条目也保存在其中。
我知道有两种方法可以解决这种情况,但我不确定应该采用哪种方法?
第一:
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
ArrayList<String> temp = new ArrayList<String>();
temp.add(name);
if (!contactList.contains(name)) {
contactList.add(name);}
第二个:
将其添加到哈希集,因为它不允许重复的条目,然后将其添加回数组列表 -
String name = getStrin(...);
contactList.add(name);
// after the loop has completed adding all elements
HashSet hs = new HashSet();
hs.addAll(contactList);
contactList.clear();
contactList.addAll(hs);
最佳答案
您应该遵循第二种方式,因为它更好,并且针对不同的值进行了优化。
关于java - 将 ArrayList 限制为仅包含 DISTINCT 条目时,哪种方法成本更高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12706949/