I am trying to remove all numbers that is divisible with some index in a TreeSet and I am using the following code
TreeSet<Integer> primes = new TreeSet();
Iterator<Integer> iter = primes.iterator();
int n = 100;
for (int i = n; i > 1; i--){
primes.add(i);
}
for (int i = 2; i < Math.sqrt(n); i ++){
while (iter.hasNext()){
int next = iter.next();
if (next % i == 0){
primes.remove(next);
}
}
}
System.out.println(primes);
But for some reason, no elements in the set gets removed
Iterator.remove()
is the only safe way to modify a collection during iteration. Use iter.remove();
while (iter.hasNext()){
int next = iter.next();
if (next % i == 0){
iter.remove();
}
}
Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. From ITERATOR
First create the Iterator
after you added the primes and then use Iterator.remove()
to not get a ConcurrentModificationException
.
TreeSet<Integer> primes = new TreeSet();
int n = 100;
for (int i = n; i > 1; i--) {
primes.add(i);
}
Iterator<Integer> iter = primes.iterator();
for (int i = 2; i < Math.sqrt(n); i++) {
while (iter.hasNext()) {
int next = iter.next();
if (next % i == 0) {
iter.remove();
}
}
}
System.out.println(primes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With