infoholic_anonymous
infoholic_anonymous

Reputation: 999

Is there a list implementation that would allow gaps?

I'm looking for a collection that would be some sort of a list that allows gaps. The objectives are:

Sample 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 "*/

Upvotes: 6

Views: 1250

Answers (2)

Thiago Negri
Thiago Negri

Reputation: 5351

You may use a Map and only set the keys you need.

You can keep the insertion order if you want, take a look: Java Class that implements Map and keeps insertion order

Upvotes: 0

Eran
Eran

Reputation: 393936

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)).

Upvotes: 4

Related Questions