gpt4 book ai didi

java - Java中如何避免循环引用

转载 作者:行者123 更新时间:2023-11-30 06:38:50 25 4
gpt4 key购买 nike

我正在尝试创建两个不同的类,它们代表用户可以选择排序的不同练习选项。选择一个类后,另一个类就不再是一个选项,因此我在不允许遵循它的两个类中创建了一个 ArrayList。

问题是,由于它们无法相互跟随,当构造这些类时,会导致无限循环,有什么方法可以避免这种情况吗?

PushPullLegs 类

public class PushPullLegs extends SortingGroup implements Serializable{
public PushPullLegs(){
this.setName("Push,Pull,Legs");
this.addCantFollow(new MuscleGroup());

SortingCategory push = new SortingCategory("Push","PPL","Push");
this.addOption(push);
SortingCategory pull = new SortingCategory("Pull","PPL","Pull");
this.addOption(pull);
SortingCategory legs = new SortingCategory("Legs","PPL","Legs");
this.addOption(legs);
}
}

肌肉组类(class)

public class MuscleGroup extends SortingGroup implements Serializable {
public MuscleGroup(){
this.addCantFollow(new PushPullLegs());
SortingCategory chest = new SortingCategory("Chest","Primary","Chest");
chest.addNewOptions(new ChestMovementPatterns());
this.addOption(chest);
SortingCategory triceps = new SortingCategory("Triceps","Primary","Triceps");
triceps.addNewOptions(new TricepMovementPatterns());
this.addOption(triceps);
SortingCategory lats = new SortingCategory("Lats","Primary","Lats");
this.addOption(lats);
SortingCategory quads = new SortingCategory("Quads","Primary","Quads");
this.addOption(quads);
SortingCategory hamstrings = new SortingCategory("Hamstrings","Primary","Hamstrings");
this.addOption(hamstrings);
}
}

最佳答案

您将使用这样的代码:

private Set<Class<? extends SortingGroup>> cantFollowClass = new HashSet<>();

public void addCantFollow(Class<? extends SortingGroup> clazz) {
this.cantFollowClass = clazz;
}

public boolean canFollow(SortingGroup group) {
return ! this.cantFollowClass.contains(group.getClass());
}

关于java - Java中如何避免循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com