Home > Mobile >  Error while mering 2 groups (Im a beginner)
Error while mering 2 groups (Im a beginner)

Time:12-05

So I have a MusicBand Class and I want to create a method that merges members of 2 different groups into one and clears the empty one.

public class MusicBand {
    private int year;
    private String name;
    private List<String> members;

    public MusicBand(String name, int year, List<String> members) {
        this.name = name;
        this.year = year;
        this.members = members;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getMembers() {
        return members;
    }

    public void setMembers(List<String> members) {
        this.members = members;
    }
    public static void transferMembers(MusicBand a, MusicBand b) {
        for (String members : a.getMembers()) {
            b.getMembers().add(members);
            a.getMembers().clear();
        }
    }
    public void printMembers(){
        System.out.println(this.members);
    }
}
public class Test4 {
    public static void main(String[] args) {
        List<String> members1 = new ArrayList<>();
        members1.add("a");
        members1.add("b");
        members1.add("c");
        List<String>members2 = new ArrayList<>();
        members2.add("a2");
        members2.add("b2");
        members2.add("c2");
        MusicBand group1 = new MusicBand("aaa",1990,members1);
        MusicBand group2 = new MusicBand("bbb",2010,members2);
        group1.printMembers();
        group2.printMembers();
        MusicBand.transferMembers(group1,group2);
    }
}

So it prints out 2 groups and then instead of merging this happens "Exception in thread "main" java.util.ConcurrentModificationException"

What can I do to fix this? Thanks in advance.

CodePudding user response:

Move your a.getMembers().clear(); method outside your for loop.

In fact your transferMembers() method could look like the following:

public static void transferMembers(MusicBand a, MusicBand b) {
    b.getMembers().add(members);
    a.getMembers().clear();
}

There is no need for a for loop at all.

CodePudding user response:

It is also bad practice to use a static method for this. So, your MusicBand class should just have a method to add members to it. So, instead of your static transferMembers(...) method you should have these two:

public void addMembers(MusicBand otherBand) {
    getMembers().addAll(otherBand.getMembers());
}

public void clear() {
    getMembers().clear();
}

You can then decide whether to call clear() from the calling class or inside the addMembers() method.

  •  Tags:  
  • java
  • Related