私は複数回表示されることがありArrayListの中の特定の要素を削除する必要があります

jcel775:

複数回、その要素が含まれていてもよいのArrayListから特定の要素を削除しようとしたとき、私はOutOfMemoryErrorが発生し、他のArrayListのエラーを取得しています。

私は指定された要素が含まれているインデックス(複数可)を除去することにより、手動の線形検索をやって試してみましたが、また、私のループでは、最初のループの後に0と等しくないだろうintとして、仕事にそれを得ることができませんでした(私があれば設定しました満足している場合、ループの先頭に0 iに割り当てます声明)。

        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));
        }
遠-アモス:

そうすることの2通りの方法があります。

  1. あなたは逆の反復を実行することができます。
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. 使用の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);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=222734&siteId=1