Java: Best way to store to an arbitrary index of an ArrayList

后端 未结 7 908
清酒与你
清酒与你 2021-01-13 11:20

I know that I cannot store a value at an index of an ArrayList that hasn\'t been used yet, i.e. is less than the size. In other words, if myArrayList.size() is 5, then if I

7条回答
  •  醉梦人生
    2021-01-13 12:10

    I could use a HashMap and use the index as a key but that's really inefficient.

    Depends. If the indices you use are very sparse, it might be a lot better to use a Map. If the indices tend to be closely together, I think there is no better way than to fill it with nulls. Just write a utility function for it that you can use over and over instead of repeating the loop everywhere you need it, something like this:

    private void padTo(List list, int size) {
        for (int i=list.size(); i

提交回复
热议问题