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

后端 未结 7 906
清酒与你
清酒与你 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:44

    If you are looking for a sparse array (where most of the indices will be empty), a Map of some sort (probably a HashMap) will be your best bet. Any array-esque solution will be forced to reserve space for all the empty indices, which is not very space-efficient, and a HashMap is fast enough for most normal purposes.

    If you will eventually fill up the array up to some n, you will need to add nulls in a loop to get to the index you want. You can make this somewhat more efficient by giving it an initial capacity of the number of elements you will eventually want to store (this prevents the ArrayList from needing to resize itself). new ArrayList(n) will work fine. Unfortunately, there is no simple way of making it a certain size to begin with except adding things in a loop when you make it.

    0 讨论(0)
  • 2021-01-13 11:50

    You can use a Map<Integer, MyClass> instead. Specifically, if you use HashMap, it will also be O(1) - though it will be slower than ArrayList.

    0 讨论(0)
  • 2021-01-13 11:54

    You can use TreeMap<key, value>, which is sorted in natural order by the value.

    Here you can keep value as the index. You can insert any value, it need not be in order. This seems the simplest solution.

    0 讨论(0)
  • 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...

    0 讨论(0)
  • 2021-01-13 12:09

    Sounds like you want a regular array:

    • You want random access
    • You want to specify some large size
    0 讨论(0)
  • 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<size; i++)
            list.add(null);
    }
    
    0 讨论(0)
提交回复
热议问题