I am attempting to write a program that iterates over a set of sets. In the example code below, I am getting an error that stating that iter.next() is of type object rather than a set of strings. I am having some other more mysterious issues with iterating over sets of sets as well. Any suggestions?
Set<String> dogs= new HashSet<String>(); dogs.add("Irish Setter"); dogs.add("Poodle"); dogs.add("Pug"); dogs.add("Beagle"); Set<String> cats = new HashSet<String>(); cats.add("Himalayan"); cats.add("Persian"); Set<Set<String>> allAnimals = new HashSet<Set<String>>(); allAnimals.add(cats); allAnimals.add(dogs); Iterator iter = allAnimals.iterator(); System.out.println(allAnimals.size()); while (iter.hasNext()) { System.out.println(iter.next().size()); } A related question with the same setup (minus the loop).
The code fragment below results in a final output that includes tildes. But I don't want to change allAnimals as I go! How can I edit extension without affecting the larger set (allAnimals).
for (Set<String> extension : allAnimals) { System.out.println("Set size: " + extension.size()); extension.add("~"); System.out.println(extension); } System.out.println(allAnimals);
someSet.clear();right after creating a set.