如何确保阵列ADAPTER不接受重复的值



我有一个带有一些pre_proped数据的自定义阵列adapter,并且要从用户输入中添加更多数据。问题是,重复值仍然添加到阵列。我的代码:

String s;//holds data from user input
for(int i=0 ; i<my_adapter.getCount() ; i++){
 MyCollection itemObject=my_adapter.getItem(i);
 //MyCollection is an object from the collection class
 String c=itemObject.toString();
     if(c.matches(s)){
     //do not add s to array adapter
}else{
   //add s to arrayadapter
    my_arrayvalues.add(new MyCollection(s));
    my_adapter.notifyDataSetChanged();
}

运行上述代码,即使值不匹配,适配器也不会发生更改。 添加了重复值。我可以如何更正?

遵循我所建议的答案后,但仍在添加重复项:更新的代码

             hs = new HashSet();
             my_arrayvalues.add(new MyCollections(s));
             hs.addAll(my_arrayvalues);
             my_arrayvalues.clear();
             my_arrayvalues.addAll(hs);
             my_adapter.notifyDataSetChanged();

您可以使用不允许重复的集合。由于您已经实现了自定义适配器,因此您可以避免将数据集ArrayAdapter的超级构造函数传递给您所需的方法。

例如,您可以使用

LinkedHashSet

,getCount方法应返回LinkedHashSet的这一点。另外,您的班级可以extend BaseAdapter而不是ArrayAdapter

使用String.equals(s)代替String.matches(s)

平等将比较平等的字符串对象。

String s;//holds data from user input
for(int i=0 ; i<my_adapter.getCount() ; i++){
 MyCollection itemObject=my_adapter.getItem(i);
 //MyCollection is an object from the collection class
 String c=itemObject.toString();
     if(c.equals(s)){
     //do not add s to array adapter
}else{
   //add s to arrayadapter
    my_arrayvalues.add(new MyCollection(s));
    my_adapter.notifyDataSetChanged();
}

!!!编辑!!!

虽然以上应该解决您的问题,但我同意其他解决方案,即您应该使用HashSet,而不是手动检查所有元素。使用HashSet或同等学历将提高性能。检查此答案是否有更好的解释。

最新更新