6

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

  • every element has some index in the collection that is meaningful.
  • the collection is to be sparse and not continuous; its size should return the number of proper elements, hence the workaround of initializing with null wouldn't work.
  • subList method is desirable to access sublists according to index intervals

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 "*/
infoholic_anonymous
  • 969
  • 3
  • 12
  • 34
  • 1
    Your requirement for the `size` method conflicts with the `List` interface. The `get` method on `List` *has* to throw an `IndexOutOfBoundsException` of the index < 0 or > `size()`, so your `size()` method *has* to return the highest indexable element that can be retrieved with the `get()` method. – Erwin Bolwidt Dec 08 '14 at 15:58

2 Answers2

4

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

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 4
    Anything that implements the `NavigableMap` interface (which includes `TreeMap`) should do, as it provides the [subMap](http://docs.oracle.com/javase/7/docs/api/java/util/NavigableMap.html#subMap%28K,%20boolean,%20K,%20boolean%29) method that satisfies the OPs need for sublists. –  Dec 08 '14 at 15:05
0

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

Community
  • 1
  • 1
Thiago Negri
  • 5,221
  • 2
  • 28
  • 39