105

I have an ArrayList suppose list, and it has 8 items A-H and now I want to delete 1,3,5 position Item stored in int array from the list how can I do this.

I am trying to do this with

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

for (int j = 0; j < i.length; j++) {
    list.remove(i[j]);
}

But after first item deleted positioned of array is changed and in the next iterate it deletes wrong element or give exception.

Augustus
  • 1,479
  • 2
  • 17
  • 31
Krishnakant Dalal
  • 3,568
  • 7
  • 34
  • 62
  • 1
    Your logic is flawed. Surely you shouldn't be thinking about the position of each item but instead thinking about the items themselves. In other words, you don't want to remove positions 1, 3 & 5 but instead you want to remove the items (wherever they are in the `List`) using `equals("B")`, `equals("D")` and `equals("F")`. Think about it. – Squonk May 23 '12 at 06:10
  • Yes I want to delete the Item but how can I match Items. Actually in real this items are in ListView and on select I want to delete this from DB and Array and refresh adapter and List – Krishnakant Dalal May 23 '12 at 06:22
  • 1
    How about removing it in the descending order of indices (sort the indices, then removing the element with the highest index first)? – nhahtdh May 23 '12 at 05:59
  • Slow option: iterate once adding the elements to a second list, iterate the second list removing from the first (optional step: return the second list to the caller) – SparK May 18 '16 at 23:27

11 Answers11

141

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • 1
    The OP's ArrayList contains `String`s, not `Integer`s (nonetheless, I agree with your observation). – Alex Lockwood May 23 '12 at 06:23
  • @Alex : This answer will work but it is as flawed as the OP's logic in their question. We're talking about `ArrayList` - why would anyone want to remove an object from an `ArrayList` based purely on position instead of testing what's at that position? The OP may well be using `String` as the object type for the `ArrayList` but your answer is really bad coding practice for generics even if it does solve the OP's particular situation. – Squonk May 23 '12 at 06:26
  • 3
    Yes, I agree with you. But the OP asked about `ArrayList`, not `ArrayList`. – Adrian Monk May 23 '12 at 06:28
  • I am completely disagree with this answer, @MisterSquonk ya convinced, solution must be generic. Moreover why I am getting downvote? – Mohammed Azharuddin Shaikh May 23 '12 at 06:31
  • @Tim : Which part of `` do you not understand? My point is that when removing any object from a list/collection purely based on position (particularly if it's not sorted) without 'testing' for what is at that position is seriously bad coding practice. – Squonk May 23 '12 at 06:34
  • @hotveryspicy : You have the closest answer as far as I'm concerned. – Squonk May 23 '12 at 06:36
  • 68
    OK, listen... I don't know what the big deal is. The OP posted his code and I responded with an answer that illustrated a possible fix. I'm sorry I didn't go above and beyond by giving a completely general solution... but as far as I can tell, the OP wasn't asking for a programming lesson. He was asking "why is this code not working?" Don't start blaming me for down-voting your answer just because you interpreted the question differently. – Alex Lockwood May 23 '12 at 06:41
  • if you have custom object, How you can do ? –  Jun 25 '15 at 10:43
30

You can remove elements from ArrayList using ListIterator,

ListIterator listIterator = List_Of_Array.listIterator();

 /* Use void remove() method of ListIterator to remove an element from List.
     It removes the last element returned by next or previous methods.
 */
listIterator.next();

//remove element returned by last next method
listIterator.remove();//remove element at 1st position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 3rd position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 5th position
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Jainendra
  • 24,713
  • 30
  • 122
  • 169
  • Its better and good practice to use ListIterator remove() method for removing objects from Collection in Java, because there may be chance that another thread is modifying the same collection and could leads to ConcurrentModificationException. – Min2 Jun 21 '18 at 03:05
10
 public void DeleteUserIMP(UserIMP useriamp) {
       synchronized (ListUserIMP) {
            if (ListUserIMP.isEmpty()) {
            System.out.println("user is empty");
        }  else {
            Iterator<UserIMP> it = ListUserIMP.iterator();
            while (it.hasNext()) {
                UserIMP user = it.next();
                if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
                    it.remove();
                    System.out.println("remove it");
                }
            }
            // ListUserIMP.remove(useriamp);

            System.out.println(" this user removed");
        }
        Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
        // System.out.println("This user Deleted " + Constants.MESSAGE_OK);

    }
}
7

As mentioned before

iterator.remove()

is maybe the only safe way to remove list items during the loop.

For deeper understanding of items removal using the iterator, try to look at this thread

Community
  • 1
  • 1
shimon001
  • 733
  • 9
  • 24
4

I assume the array i is ascend sorted, here is another solution with Iterator, it is more generic:

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

Iterator<String> itr = list.iterator();
int pos = 0;
int index = 0;
while( itr.hasNext() ){
    itr.next();
    if( pos >= i.length ){
        break;
    }
    if( i[pos] == index ){
        itr.remove();
        pos++;
    }

    index++;
}
DàChún
  • 4,751
  • 1
  • 36
  • 39
3
String[] mString = new String[] {"B", "D", "F"};

for (int j = 0; j < mString.length-1; j++) {
        List_Of_Array.remove(mString[j]);
}
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
2

How about this? Just give it a thought-

import java.util.ArrayList;

class Solution
{
        public static void main (String[] args){

             ArrayList<String> List_Of_Array = new ArrayList<String>();
             List_Of_Array.add("A");
             List_Of_Array.add("B");
             List_Of_Array.add("C");
             List_Of_Array.add("D");
             List_Of_Array.add("E");
             List_Of_Array.add("F");
             List_Of_Array.add("G");
             List_Of_Array.add("H");

             int i[] = {1,3,5};

             for (int j = 0; j < i.length; j++) {
                 List_Of_Array.remove(i[j]-j);
             }

             System.out.println(List_Of_Array);

        }


}

And the output was-

[A, C, E, G, H]
sgowd
  • 2,242
  • 22
  • 29
2

Try it this way,

ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");

int i[] = {5,3,1};

for (int j = 0; j < i.length; j++) {
    List_Of_Array.remove(i[j]);
}
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Khan
  • 7,585
  • 3
  • 27
  • 44
2

If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="

        List_Of_Array1.addAll(List_Of_Array);
Rahul Gupta
  • 5,275
  • 8
  • 35
  • 66
2

remove(int index) method of arraylist removes the element at the specified position(index) in the list. After removing arraylist items shifts any subsequent elements to the left.

Means if a arraylist contains {20,15,30,40}

I have called the method: arraylist.remove(1)

then the data 15 will be deleted and 30 & 40 these two items will be left shifted by 1.

For this reason you have to delete higher index item of arraylist first.

So..for your given situation..the code will be..

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
-1

if you need to remove end item in list can use this code

 if(yourList.size() != 0){
   yourList.remove(yourList.size()-1);
 }

or maybe you need to remove a time after select item in list

if(selected){// boolean for checked add or remove
   yourList.add(position , id); // add to list by position can use your list position
}else{
   if(yourList.size() != 0){ 
   yourList.remove(position);
 }
}