Is there a list implementation that avoids spaces?

I am looking for a collection that will be a kind of list that allows spaces. Objectives:

  • each item has some index in the collection, which makes sense.
  • the collection should be rare and not continuous; its size should return the number of valid elements, so a null initialization workaround will not work.
  • subList desirable to access subList according to index intervals

Usage example:

 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 "*/ 
+6
source share
2 answers

Use Map<Integer,Integer> . The key will be your index, and the value will be the value of the list.

For your sub-system requirement, perhaps TreeMap<Integer,Integer> will work, as it preserves the sorting of keys and simplifies iteration over the sub-list.

Of course, this means that you cannot use the List interface. If you must use the List interface, you can create your own List implementation supported by TreeMap (for example, list.add(5,3) will call map.put(5,3) ).

+5
source

You can use Map and install only the keys you need.

You can keep the insertion order, if you want, look: a Java class that implements a map and preserves the insertion order

0
source

Source: https://habr.com/ru/post/979280/


All Articles