Remove from a List of Integers

3

I have a ImageButton o imgB1 :

When I click on imgB1 , I add it to a list of integers, 1. If you re-click the imagB1 , it removes the 1 and places the 6.

List<Integer> list = new ArrayList<>();

When I click:

if (ContemLista(v) == false)
{
   list.add(1);
}
else
{
   list.remove(1);
   list.add(6);
}

However, the number 1 is still in list . What am I doing wrong?

    
asked by anonymous 30.01.2017 / 13:29

3 answers

4

The remove method of this structure ( List<Integer> list = new ArrayList<>(); ) has two parameters for removal, one is of type Object and the other is index (index) of position , in your case looks like you were removing a position that was not of value 1 but of index 1.

To remove it could then be in two ways:

Removing by value:

lista.remove((Object)1);

Removing by index from position find:

int ret = lista.indexOf(1);
if (ret > -1) lista.remove(ret);

Java and its crazy programming.

References

30.01.2017 / 13:48
4

The interface List<Integer> of Java has 2 methods remove :

Integer java.util.List.remove(int index) : Removes the element from the list in the index (index) specified. If it exists, the value in index is returned, otherwise it returns null ;

boolean java.util.List.remove(Object o) : Removes the specified object from the list. If it exists, it returns true , otherwise it returns false .

The evoked method will always be the one that best matches the passed parameter. In your case, you are passing int , so the evoked method is remove(int index) .

For you to evoke the remove(Object o) method, you should specifically pass Integer accordingly lista.remove(Integer.valueOf(1)) .

Sample code:

public class RemoveFromListInteger {

    public static void main(String[] args) {
        List<Integer> lista = new ArrayList<>();
        lista.add(1);
        lista.add(2);
        lista.add(3);
        lista.add(4);

        lista.remove(1);                    //Remove na posição 1, ou seja, o valor 2
        System.out.println("Depois de remover na posição 1");
        lista.forEach(System.out::println);

        lista.remove(Integer.valueOf(1));   //Remove o valor 1
        System.out.println("\n\nDepois de remover o valor 1");
        lista.forEach(System.out::println);
    }
}
    
30.01.2017 / 13:52
0

When you use remove of interface List you pass an index to remove as a parameter or value. In your case it may be that it has more than one value in the list and if yes it is removing the first occurrence or else it is always removing index 1 depends on which method you called, iterate your list and do the following: p>

for (Integer num : list) {
            if (num == 1) {
                list.remove(Integer.valueOf(1));
            }
        }
    }

It's just one of the options.

    
30.01.2017 / 13:39