I need to remove specific elements in an ArrayList which may appear more than once

jcel775 :

I am getting an OutOfMemoryError and other ArrayList errors when trying to remove specific elements from an ArrayList which may contain that element more than once.

I have tried doing a manual linear search by removing the index(s) which contain the specified element, but also could not get it to work, as int i in the loop would not equal 0 after the first loop (I set up an if statement which would assign i to 0 at the very beginning of the loop if satisfied).

        ArrayList<String> s = new ArrayList<String> (); /* List which will have some of its elements removed */
        ArrayList<String> rem = new ArrayList<String> (); /* List containing the elements which will be removed */
        ArrayList<Boolean> bool = new ArrayList<Boolean> (); /* List which will indicate if the removal of an element taken place in the previous loop */
        /**/
        s.add("hello");
        s.add("hello");
        s.add("your");
        s.add("hi");
        s.add("there");
        s.add("hello");
                /**/
        rem.add("hello");
        rem.add("hi");
        /**/
        int len=s.size();
        /*loop for bool*/
        for (int j=0; j<len; ++j) {
            /* loop for rem */
            for (int i=0; i<rem.size(); ++i) {
                if (j>=1) {
                    if (bool.get(j-1)==true) i=0; /* If an element (from rem) had been removed from s in the previous loop, then it will continue looking for looking for that same element (from rem) until it has removed all instances of it. Then it moves to the next element in rem and removes those elements from s and so on. **/
                }
                if (s.contains(rem.get(i))) {
                    s.remove(rem.get(i));
                    bool.add(true); 
                }
                else bool.add(false); 
            }
        }
        /* prints ArrayList<String> s after it has been through the removal process */
        for (int i=0; i<s.size(); ++i) {
            System.out.println(s.get(i));
        }
Zhiyuan-Amos :

There are 2 ways of doing so:

  1. You can perform reverse iteration:
ArrayList<String> s = new ArrayList<>();
s.add("hello");
// add more Strings...

ArrayList<String> rem = new ArrayList<>();
rem.add("hello");
// add more Strings to remove...

for (int i = s.size() - 1; i >= 0; i++) {
    if (rem.contains(s.get(i)) {
        s.remove(i);
    }
}
  1. Using removeAll:
ArrayList<String> s = new ArrayList<>();
s.add("hello");
// add more Strings...

ArrayList<String> rem = new ArrayList<>();
rem.add("hello");
// add more Strings to remove...

s.removeAll(rem);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111968&siteId=1