I'm looking for a collection that would be some sort of a list that allows gaps. The objectives are:
null
wouldn't work.subList
method is desirable to access sublists according to index intervalsSample use case:
List<Integer> list = /* ? */;
list.add(0,5);
list.add(1,4);
list.add(5,3);
for( Integer i : list )
{
System.out.print( i + " " );
}
/* desired output : "5 4 3 "*/
Use a Map<Integer,Integer>
. The key would be your index and the value the value of the list.
For your subList requirement, perhaps TreeMap<Integer,Integer>
would work, as it keeps the keys sorted and makes it easy to iterate over a sub-list.
Of course this means you can't use the List
interface. If you must use the List
interface, you can make your own List
implementation backed by a TreeMap
(for example, list.add(5,3)
would call map.put(5,3)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With