try this
list.removeAll(Arrays.asList(2));
it will remove all elements with value = 2
you can also use this
list.remove(Integer.valueOf(2));
but it will remove only first occurence of 2
list.remove(2) does not work because it matches List.remove(int i) which removes element with the specified index
try this
list.removeAll(Arrays.asList(2));
it will remove all elements with value = 2
you can also use this
list.remove(Integer.valueOf(2));
but it will remove only first occurence of 2
list.remove(2) does not work because it matches List.remove(int i) which removes element with the specified index
There are two versions of remove() method:
ArrayList#remove(Object)that takes anObjectto remove, andArrayList#remove(int)that takes anindexto remove.
With an ArrayList<Integer>, removing an integer value like 2, is taken as index, as remove(int) is an exact match for this. It won't box 2 to Integer, and widen it.
A workaround is to get an Integer object explicitly, in which case widening would be prefered over unboxing:
list.remove(Integer.valueOf(2));
Processing 1.0 - Processing Discourse - removing elements of an arrayList
(Java) Can't remove element from List/ArrayList, always gives NullPointerException or ConcurrentModificationException.
java - C# is fantastic, if only List 'd respect Remove&Return - Software Engineering Stack Exchange
How does an ArrayList remove an element from an array?
Videos
I have an ArrayList that has some elements that should be removed, or not even added in the first place, but it always throws on of the two exceptions mentioned in the title.
So I have the following arraylist:
List<String> doc = new ArrayList<String>();
I add elements to it like this (this is all working so far, println prints every single element perfectly):
BufferedReader reader;
reader = new BufferedReader(new StringReader(extractor.getText()));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
doc.add(line);
}
reader.close();But I have some repeating elements that I want to remove, these all contain ".lap".
So I try to remove it in a for-each loop:
for (String s : doc) {
if (s.contains(".lap")) {
doc.remove(s);
}
}Which give me a ConcurrentModificationException.
I looked into it and on StackOverflow they said an Iterator should be used, so I did the following:
Iterator<String> i = doc.iterator();
while (i.hasNext()) {
String s = i.next();
if (s.contains(".lap")) {
i.remove();
}
}This one throws a NullPointerException.
So I tried not removing elements, but skipping them all together when reading from the input, so I modified the first block of code like this:
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
if (!line.contains(".lap")) {
doc.add(line);
}
}
reader.close();This one also throws a NullPointerException.
So how should I remove (or not even add in the first place) some specific lines/elements in an ArrayList? I even looked for an answer on the 2nd Google page and still nothing.