你能直接从3D arraylist中删除1D arraylist吗?

时间:2018-05-13 22:44:36

标签: java arraylist

为了澄清,我想知道你是否可以直接从3D ArrayList中删除1D arraylist而不必首先找到包含所述1D阵列的2d arraylist。

这很难解释,所以这是一个例子:

ArrayList<String> berries=new ArrayList<String>();
berries.add("blueberry");
berries.add("strawberry");

ArrayList<ArrayList<String>> fruit=new ArrayList<ArrayList<String>>();
fruit.add(berries);

ArrayList<ArrayList<ArrayList<String>>> food=new ArrayList<ArrayList<String>>();
food.add(fruit);

//Can I do this?
food.remove(berries);

//Or do I have to do something like this?
food.get(food.indexOf(fruit)).remove(berries);

//I want to remove the ArrayList itself, not just its contents

我只想简化示例,因此假装ArrayLists包含的元素多于显示的元素。

2 个答案:

答案 0 :(得分:0)

您无法在remove的实例上使用food,因为它只包含fruit列表和equals ArrayList方法}不会检查列表的子集。

要获得您馆藏中的浆果,您必须首先遍历fruit

答案 1 :(得分:0)

如果您执行此代码(我在您的示例中添加了更多食物),您可以自己总结答案:

public static void main(String[] args) {

    ArrayList<String> berries = new ArrayList<>();
    berries.add("blueberry");
    berries.add("strawberry");

    ArrayList<String> apples = new ArrayList<>();
    apples.add("green apple");
    apples.add("red apple");

    ArrayList<ArrayList<String>> fruit = new ArrayList<>();
    fruit.add(berries);
    fruit.add(apples);

    ArrayList<ArrayList<ArrayList<String>>> food = new ArrayList<>();
    food.add(fruit);

    ArrayList<String> freshMeat = new ArrayList<>();
    freshMeat.add("pork");

    ArrayList<ArrayList<String>> meat = new ArrayList<>();
    meat.add(freshMeat);
    food.add(meat);

    System.out.println("food " + food);

    food.get(food.indexOf(fruit)).remove(berries);
    System.out.println("food " + food);

}

输出结果为:

food [[[blueberry, strawberry], [green apple, red apple]], [[pork]]]
food [[[green apple, red apple]], [[pork]]]

此外,这种编程不适合OO语言。 我的建议是制作interfaceabstract class Food类型,然后使用继承......