I want to keep the indices of the items in a Java List fixed.
Example code:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Double> a = new ArrayList<Double>();
a.add(12.3);
a.add(15.3);
a.add(17.3);
a.remove(1);
System.out.println(a.get(1));
}
}
This will output 17.3. The problem is that 17.3 was on index 2 and now it’s on index 1!
Is there any way to preserve the indices of other elements when removing an element? Or is there another class more suitable for this purpose?
Note: I don’t want a fixed size Collection.
You might want to use
java.util.SortedMapwithintkeys:SortedMapis a variable-size CollectionList‘s indices)No implementation of
java.util.List#remove(int)may preserve the indices since the specification reads: