Issue
I want to get list from list of lists like
List<List<Item>> items = new ArrayList<List<Item>>(4);
List<Item> item = items.get(1);
This it not working.
I want a type ArrayList<Item>
.
Solution
When you use the ArrayList(int)
constructor, it creates an empty list. It cannot fill the list with instances of the given type, it fills it with null.
Another remark: items.get(1)
would give you the second element in the list, because indices in Java start at 0. The first element would be accessed by items.get(0)
.
Here is how you could fill the list with empty lists:
List<List<Item>> items = new ArrayList<>();
for (int i=0; i < 4; i++) {
items.add(new ArrayList<>());
}
List<Item> item = items.get(0); // an empty ArrayList
You can also make the ArrayList unmodifiable by wrapping it with Collections.unmodifiableList(List)
.
Or even better, only make a new list when needed.
private List<List<Item>> items = new ArrayList<>(4);
public List<Item> getItem(int index) {
List<Item> ret = items.get(index);
if (ret == null) {
ret = new ArrayList<>();
items.set(index, ret);
}
return ret;
}
However, if you don't want to change the size of the list, may I suggest just a normal array?
Item[][] items = new Item[4][];
// OR
List<Item>[] items = new List<Item>[4]; // however this combination is pretty weird
Answered By - Wasabi Thumbs
Answer Checked By - Clifford M. (JavaFixing Volunteer)