I'm having some troubles with an excersise from my programming class.
I had a class like this:
UML of the class
And I have to make a public method that return the total quantity of sub sectors from an sector.
This is the code for the entire class:
public class Sector {
private int number;
private String name;
private String type;
private ArrayList<Sector> sectors = new ArrayList<>();
public Sector(int number, String name, String type) {
this.number = number;
this.name = name;
this.type = type;
}
and the recursive method is this
public ArrayList<Sector> getTotalSectors(Sector sector, ArrayList<Sector> sectors) {
sectors.add(this);
if (sector.getSectors() != null) {
for(Sector sector1 : sector.getSectors()) {
getTotalSectors(sector1, sectors);
}
}
return sectors;
}
But i can't make it work, i get this when i try to call the method in the main
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
** Main class **
Sector s1 = new Sector(100, "sales", "sales");
Sector s1_1 = new Sector (101, "minor sales", "minor");
Sector s1_2 = new Sector (102, "mayor sales", "mayor");
Sector s1_2_1 = new Sector (102, "lala sales", "lalala");
s1.getSectors().add(s1_1);
s1.getSectors().add(s1_2);
s1_2.getSectors().add(s1_2_1);
s1.getTotalSectors(s1, s1.getSectors());
Any idea of what i'm doing wrong?
Inside your getTotalSectors method, replace your for loop within the if-structure with the code below. The exception you are getting should not happen if you use the Iterator class.
Iterator<Sector> iter = sectors.iterator();
while (iter.hasNext()) {
Sector sector1=iter.next();
getTotalSectors(sector1, sectors);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.