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

后端 未结 7 946
清酒与你
清酒与你 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 11:55

    HashMap is probably much less inefficient than you think, try it. Otherwise, I can think of no way of doing it more elegantly than looping and filling with null. If you want elegance of exposition at least, then you could always subclass ArrayList and add an expandingSet(position, value) method to hide all the looping and such, or something. Perhaps this isn't an option though? If not just have a utility method somewhere else for it, but this is not as nice imho, though it will work also with other types of list too I guess...

    Perhaps a wrapper class would be the best of both worlds, or perhaps it would just incur unnecessary overhead...

提交回复
热议问题