简体   繁体   English

ArrayLists的ArrayList,默认值

[英]ArrayList of ArrayLists, default values

I'm a beginner in Java and I'm trying to create an ArrayList that stores ArrayLists which hold integers. 我是Java的初学者,我正在尝试创建一个存储包含整数的ArrayLists的ArrayList。 I already know the size I want for the outer ArrayList and want to store the inner ArrayLists. 我已经知道外部ArrayList的大小,并且想要存储内部ArrayLists。 I would then for example want to add all dog ID numbers to the ArrayList stored in the first index of the outer ArrayList, cat ID numbers in the second, and lizard ID numbers in the third.This will happen in a random order so I want the outer ArrayList to have it's size already initialized so I can send an ID number to it's correct inner list when I come across it . 然后,我想要将所有狗ID号添加到存储在外部ArrayList的第一个索引中的ArrayList,第二个中的cat ID号和第三个中的蜥蜴ID号。这将以随机顺序发生,所以我想要外部ArrayList已经初始化了它的大小,所以当我遇到它时,我可以发送一个ID号给它正确的内部列表。 This is what I did: 这就是我做的:

ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>(capacity);
ArrayList<Integer> inner = new ArrayList<Integer>(); 
    for (int i = 0; i < capacity; i++) {
        outer.add(null);
    }   

Would initializing those indices to null increase the size to whatever number is stored in capacity and allow me to later add a dog to inner by doing outer.get(3).add(10) and then outer.get(0).add(22) ? 将这些索引初始化为null会将大小增加到capacity存储的任何数量,并允许我稍后通过执行outer.get(3).add(10)然后将outer.get(0).add(22)添加到内部。 outer.get(0).add(22)

I also thought about doing this: 我也考虑过这样做:

ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>(capacity);
ArrayList<Integer> inner = new ArrayList<Integer>(); 
    for (int i = 0; i < capacity; i++) {
        outer.add(inner);
    }   

But don't know if adding inner would actually initialize all indices in outer to Integer ArrayLists or if they would be referencing the "inner" variable itself or something like that. 但是不知道添加inner是否实际上将outer所有索引初始化为Integer ArrayLists,或者它们是否会引用“内部”变量本身或类似的东西。

ArrayList has size (the number of elements) and capacity (the number of elements it can hold before it needs to automatically expand) which can be used for optimization, for now you can safely ignore capacity and just add and remove elements based on your needs. ArrayList具有size (元素数量)和capacity (它需要自动扩展之前可以容纳的元素数量),可用于优化,现在您可以安全地忽略capacity ,只需根据需要添加和删除元素。

Create the outer array with: 创建外部数组:

ArrayList<ArrayList<Integer>> outer = new ArrayList<>();

And then add all the inner arrays you need: 然后添加所需的所有内部数组:

for (int i = 0; i < capacity; i++) {
    outer.add(new ArrayList<Integer>());
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM