pmb
pmb

Reputation: 2327

how to remove one item from arrayList

Let's pretend I have

List<Integer> mIds = new ArrayList<Integer>();
mIds.add(0,10);
mIds.add(1,10);
mIds.add(2,10);

I want to remove only one item of the listview but when I do this it removes all the items from the ArrayList. Do you know why?

int j=-1;
for (int i=0; i < mIds.size(); i++){
     if (mIds.get(i) == modifier.getId()){
         j=i;
         break;
     }
}
if (j != -1){
    mIds.remove(j);
}

EDIT: Sorry guys my problem was another; but I thought it is related on of removing list items. Thanks to everyone for the help

Upvotes: 1

Views: 1148

Answers (5)

mayurc
mayurc

Reputation: 265

mIds.remove(2) will remove the element on index 2.

mIds.remove(Integer.valueOf(10)) will remove the first occurrence, if present. In this case it is present.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

If you consider the value to remove element from the List, all element in the List will remove since all element has same value.

Consider the index to remove element

So just use

 List<Integer> mIds = new ArrayList<Integer>();
 mIds.add(0,10);
 mIds.add(1,10); // *
 mIds.add(2,10);

 mIds.remove(1); // 1 is index 

Now * element will remove.

For your case

mIds.remove(modifier.getId()); 

Now consider your code.

    List<Integer> mIds = new ArrayList<Integer>();
    mIds.add(0,10);
    mIds.add(1,10);
    mIds.add(2, 10);

    int j=-1;
    for (int i=0; i < mIds.size(); i++){
        if (mIds.get(i) == 10){ // 0th element is 10
            j=i; //then j=0
            break; // breaks the for loop
        }
    }
    if (j != -1){ // j=0 and this is true
        mIds.remove(j); // now 0th element will remove
    }

So your code is works fine. There is no way to remove all element since this remove() runs out side a loop, So definitely one or zero element will remove.

Upvotes: 1

AbuQauod
AbuQauod

Reputation: 919

List_Of_Array.remove(index);

then update it

notifyDataSetChanged();

Upvotes: 0

Sebastian Łaskawiec
Sebastian Łaskawiec

Reputation: 2737

I guess you're using wrong argument in remove method. In the Collection interface you have this method:

List has also a remove method:

But in this case you are removing object at some specific index.

You can try moving element using method in Collection interface:

mIds.remove(Integer.valueOf(j));

Upvotes: 1

nKn
nKn

Reputation: 13761

I think you're mixing up two implementations of remove(). One receives an Object, the other an int, ant the behavior is distinct on each case.

Upvotes: 0

Related Questions