首页 > 解决方案 > 处理数组列表的数组列表,每个数组都有不同的对象

问题描述

我有这个,三个不同的数组列表:

ArrayList<type1> alista = new ArrayList<>();
ArrayList<type2> blistb = new ArrayList<>();
ArrayList<type3> clistc = new ArrayList<>();

然后我创建一个新的数组列表并将这 3 个数组列表放入其中:

ArrayList<Object> all_lists = new ArrayList<Object>();
all_lists.add(alista);
all_lists.add(blistb);
all_lists.add(clistc);

如何在 all_lists:alista、blistb 和 clistc 中添加或删除对象?我想在我的 main() 中的方法之间来回传递这个 all_lists。我知道这样做可能是错误的,但我想先让它发挥作用,然后再通过做得更好来解决这个问题。

例如,我如何从中获取 blistb,然后添加我创建的一种 type2,然后删除一种 type2(来自 blistb)。然后将其放回(或创建新的 all_lists?)到 all_lists 中?

标签: javaobjectarraylist

解决方案


如果我理解正确,您希望能够传递所有数据并更改列表。首先,我会将您的列表类型更改为 List 界面。这不是您的代码的功能,但如果您想在将来更改 List 实现,它会更容易,并且它还保存了一些字符:

List<Type1> alista = new ArrayList<>();
List<Type2> blistb = new ArrayList<>();
List<Type3> clistc = new ArrayList<>();

我们将对 all_lists 做同样的事情,同时将其泛型类型更改为 List 以使以后的生活更轻松:

List<List<Object>> allLists = new ArrayList<Object>();

(If Type1, Type2 and Type3 have some common ancestor that they all extend from, change the Object above to that type.)

To get one of your lists, blistb for instance, you need to know it's position in all_lists:

List<Type2> blistbReference = allLists.get(1); // Index starts from 0

This will probably be hard to maintain and to keep track of. There is also a risk that some future code change changes the order which will cause errors and headaches.

A better way to handle your lists would be to wrap them in a data object:

public class AllLists {
    private List<Type1> alista;
    private List<Type2> blistb;
    private List<Type3> clistc;

    public AllLists(List<Type1> alista, List<Type2> blistb, List<Type3> clistc) {
        this.alista = alista;
        this.blistb = blistb;
        this.clistc = clistc;
    }

    public List<Type1> getAlista() {
        return alista;
    }

    public List<Type1> getBlistb() {
        return blistb;
    }

    public List<Type1> getClistc() {
        return clistc;
    }
}
// ......

    AllLists allLists = new AllLists(alista, blistb, clistc);

You can now get your lists easily from the AllLists object and modify them as you like.

Type2 t = new Type2;
allLists.getBlistb().add(t);

You don't need to "put the list back" since Java is pass by reference. When you get the blistb from allLists, you are getting a reference to the same list object. Any changes to the reference is a change to the original list.

I changed type and variable names to be more standardized.


推荐阅读