如何避免ExpandableListview的ArrayList中的重复值

时间:2017-07-21 11:10:35

标签: android expandablelistview

我不确定这个

中有什么问题
 HashMap<String, List<String>> expd = new HashMap<String, List<String>>();
   ArrayList<String> hello = new ArrayList<String>();
    ArrayList<String> hello1 = new ArrayList<String>();
    String tt="root,root1";
   n=tt.split(",");
    for(i=0;i<=n.length-1;i++){
        if(n[i]!=null){
            //Db event listener
            hello = new ArrayList<String>();
            hello.add("test");
            hello.add("test1");
            expd.put(n[i],hello);


        }

    }

    List<String> tests = new ArrayList<String>(expd.keySet());
    ExpandableListAdapter news;
    news = new CustomExpandableListAdapter(this,tests,expd);
    expandableListView.setAdapter(news);

所以在这个,test和test1被添加到root和root1两次,所以它结束了root&gt; test,test1,test,test1

有没有人有任何输入来避免这种情况?

2 个答案:

答案 0 :(得分:0)

您应该使用 HashSet 而不是 ArrayList

  

此类实现Set接口,由哈希表支持   (实际上是一个HashMap实例)。它不能保证   集合的迭代顺序;特别是,它并不保证   订单将随着时间的推移保持不变。

ArrayList 允许重复,而 HashSet 不强允许 重复< /秒>

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

示例

HashSet<String> hsetOBJ = new HashSet<String>();
    hsetOBJ.add("ONE");
    hsetOBJ.add("ONE");
    hsetOBJ.add("TWO");

   System.out.println(hsetOBJ);//[ONE, TWO]

您可以尝试使用

 HashMap<String, HashSet<String>> expd = new HashMap<String, HashSet<String>>();
   HashSet<String> hello = new HashSet<String>();
   HashSet<String> hello1 = new HashSet<String>();

   String tt="root,root1";
   n=tt.split(",");
    for(i=0;i<=n.length-1;i++){
        if(n[i]!=null){
            //Db event listener
            hello = new HashSet<String>();
            hello.add("test");
            hello.add("test1");
            expd.put(n[i],hello);


        }

    }

    List<String> tests = new ArrayList<String>(expd.keySet());
    ExpandableListAdapter news;
    news = new CustomExpandableListAdapter(this,tests,expd); // Change your Parameter; Set HashSet on that class
    expandableListView.setAdapter(news);

答案 1 :(得分:0)

试试这个:

HashMap<String, List<String>> expd = new HashMap<String, List<String>>();
    ArrayList<String> hello1 = new ArrayList<String>();
    String tt="root,root1";
   n=tt.split(",");
    for(i=0;i<=n.length-1;i++){
        if(n[i]!=null){
            //Db event listener
            ArrayList<String> hello = new ArrayList<String>();
            hello.add("test");
            hello.add("test1");
            expd.put(n[i],hello);


        }

    }

    List<String> tests = new ArrayList<String>(expd.keySet());
    ExpandableListAdapter news;
    news = new CustomExpandableListAdapter(this,tests,expd);
    expandableListView.setAdapter(news);