Skip to content

Instantly share code, notes, and snippets.

@AlinaWithAFace
Last active February 15, 2018 02:39
Show Gist options
  • Save AlinaWithAFace/b153c052cc87c30365e3f6e813afa82a to your computer and use it in GitHub Desktop.
Save AlinaWithAFace/b153c052cc87c30365e3f6e813afa82a to your computer and use it in GitHub Desktop.
Some iterator basics and how concurrent modification errors happen
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Collection<Dog> doggos = new ArrayList<>();
doggos.add(new Dog("Fido"));
doggos.add(new Dog("Spot"));
doggos.add(new Dog("Lucy"));
System.out.println(doggos);
for (Dog d : doggos) {
if (d.name.equals("Spot")) {
System.out.println(d.toString());
}
}
Iterator<Dog> dogIterator = doggos.iterator();
while (dogIterator.hasNext()) {
if (dogIterator.next().name.equals("Spot")) {
//doggos.add(new Dog("Spotty Doggo")); /// ConcurrentModificationException
//dogIterator.add(new Dog("Spotty Doggo")); /// Cannot find symbol compiler error
//doggos.remove(dogIterator.next()); // ConcurrentModificationException
dogIterator.remove(); // Spot went off to the big farmhouse in the sky.
}
}
System.out.println(doggos);
}
}
class Dog {
String name;
Dog(String dogName) {
name = dogName;
}
@Override
public String toString() {
return ("Am dog named " + name);
}
}
class C {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
for (String arguments : args) /// For every argument given
if (!set.add(arguments)) /// If the set does not already have a copy of a given argument, add it to the list. It it's already in the list, continue to...
System.out.println("Already in the set: " + arguments); /// ...print it on the next line
System.out.println(set.size() + " in set: " + set); /// Then print out the set
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment