How better to test and create a new list, if it does not exist?
I only found this solution:
private List<List<Action>> actionList = Lists.newArrayList();
...
f(int index){
Optional<List<Action>> optionalActionList = Optional.fromNullable(actionList.get(index));
if (!optionalActionList.isPresent()) {
actionList.add(new ArrayList<Action>());
}
actionList.get(index).add(index, new Action());
}
Maybe I should change the structure of storage? (The order of addition. Ability to add both the beginning and the end of the list. Are important in both lists).
Can use Google Guava if need.
It’s not clear what the
Optionalis really buying you here. I see the value ofOptionalas communicating between methods, or in storage.Additionally, I don’t think the code is doing what you think it is – you’re asking for the list at a particular index, but then if the value at that index is null, you’re adding a new list at the end. It sounds like you want:
Note that I’m not using
add(index, new Action())at the end – at it was very unclear why you’d want to do so. You’ve already got to the right list usingindex– why would you useindexagain?The above assumes that the “outer” list is already the right size, but filled with nulls for “absent” lists. If that’s not the case, you’ll need to detect when
indexis beyond the bounds of the current outer list.Basically, if the above doesn’t help, please give more information as your question is currently unclear.