如何检查ArrayList直到最深的位置?

时间:2018-10-12 18:39:43

标签: java arraylist

我有一个主类Item,子类BundleItem,ProductItem和一个Order类。

订单类创建一个ArrayList列表,可以在其中添加项目。 BundleItem还会创建一个ArrayList捆绑包,可以在其中添加商品(带有折扣的商品捆绑包)

方法(两次和BundleItem一次)

addItem(Item item) {
list.add(item) ///for order
bundle.add(item) ///for bundle
}

因此,一个捆绑包可以包含另一个捆绑包,但是如果捆绑包像间接包含自身一样,问题就开始了

bundle1.addItem(bundle1);

因为如果我使用getTotalPrice()或打印方法,则程序会由于无尽的bundle1(bundle1中bundle1中的bundle1等而导致崩溃)(抱歉,忘记了这个词)

我所做的是检查项目是否已在捆绑包中,并且仅在为false时添加

public void addItem(Item item) {
    for (Item position:bundle) {
        if (position == item) {
            System.out.println("You cannot put the same bundle in itself!");
        } else {
            bundle.add(item);
        }
    }
}

但这还不够...因为bundle1可以包含bundle 2,bundle2也包含bundle1,这会导致相同的问题... 那么如何扩展代码,以便如果该位置是BundleItem,它会更深入并在那里进行检查?

非常感谢您的帮助!

亲切的问候 Akagex

2 个答案:

答案 0 :(得分:0)

如果我了解您的要求,我想我已经基本了解了您想做什么。

我为您进行了伪编码,但是基本上,在无法重现您的特定问题的情况下,您可能想要这样的东西(可能会有很多方法可以做到这一点,这就是我的想法上)

public void addItem(Item item) {
    //if it's the same then that's bad right?
    boolean isSame = isItself(bundle, item);
    if (isSame) {
        System.out.println("You cannot put the same bundle in itself!");
    } else {
        bundle.add(item);
    }
}

private boolean isItself(bundle, item){
    //Check each item in the bundle
    for (Object position:bundle) {
        //If it matches itself then return true, it's itself.
        if(position.equals(item)){
            return true;
        }
        //If it's a bundle item then recurse down to see if it matches itself
        if(position instanceof BundleItem){
            return isItself(position, item);
        }
    }
    //once everything has been checked, it nothing matches and we've gone down as far as we can go, then return false
    return false;
}

希望这会有所帮助。

答案 1 :(得分:-1)

您可以在BundleItem中创建一个检查其自身项目的方法。我建议您阅读一些有关Recursive functions的内容。他们很有趣!

这是您可以在BundleItem中创建方法的示例。

public boolean addBundle(Bundle bundle2) {
    if (bundle2 == this) {
        return false;
    }

    if (bundle2 == null) {
        this.bundle2 = bundle2;
    } else {
        bundle2.addBundle(bundle2);
    }fi

    return true;
}
相关问题