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.SortedMap
with int
keys:
import java.util.*;
public class Test {
public static void main(String[] args)
{
SortedMap<Integer, Double> a = new TreeMap<Integer, Double>();
a.put(0, 12.3);
a.put(1, 15.3);
a.put(2, 17.3);
System.out.println(a.get(1)); // prints 15.3
System.out.println(a.get(2)); // prints 17.3
a.remove(1);
System.out.println(a.get(1)); // prints null
System.out.println(a.get(2)); // prints 17.3
}
}
SortedMap
is a variable-size CollectionList
's indices)No implementation of java.util.List#remove(int)
may preserve the indices since the specification reads:
Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
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