简体   繁体   English

ArrayList的递归方法

[英]Recursive method with ArrayList

I'm having some troubles with an excersise from my programming class. 我在学习编程课程时遇到了一些麻烦。

I had a class like this: 我上过这样的课:

UML of the class 该类的UML

在此处输入图片说明

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. 在您的getTotalSectors方法中,用下面的代码替换if-结构内的for循环。 The exception you are getting should not happen if you use the Iterator class. 如果使用Iterator类,则不会发生所发生的异常。

   Iterator<Sector> iter = sectors.iterator();
    while (iter.hasNext()) {
    Sector sector1=iter.next();
    getTotalSectors(sector1, sectors);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM