String Arraylist get the item starting with this string

后端 未结 5 1701
长情又很酷
长情又很酷 2021-02-09 15:35

I have a array list in which I bind the data This is a example

MyStrings =new ArrayList();
MyStrings.add(\"Dog\");
MyStrings.add(\"Cat\");
MyString         


        
5条回答
  •  抹茶落季
    2021-02-09 16:34

    If you want to remove items that don't match from MyStrings rather than create a new ArrayList you will need to use an Iterator as this is the only safe way to modify a ArrayList while iterating over it.

    myStrings = new ArrayList();
    myStrings.add("Dog");
    myStrings.add("Cat");
    myStrings.add("Can");
    myStrings.add("Ant");
    myStrings.add("Str");
    String sweet="c";
    
    sweet = sweet.toLowerCase();
    Iterator i = myStrings.iterator();
    
    while (i.hasNext()) {
      if (! i.next().toLowerCase().startsWith(sweet)) {
        i.remove();
      }
    }
    

提交回复
热议问题