How to save List index in Java

I want the indices of the elements in the Java list to be fixed.

Code example:

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 exit 17.3. The problem is that it 17.3was at index 2, and now it is at index 1!

Is there a way to keep indices of other elements when deleting an element? Or is there another class more suitable for this purpose?

Note. I do not need a fixed size collection.

+5
source share
6 answers

You can use java.util.SortedMapwith the keys int:

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 collection
  • , ( List)

java.util.List#remove(int) , :

( ). ( ). , .

+5

a.remove(1) a.set(1, null). , "" .

+5

, java.util.Map.

+4

null:

:

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.set(1, null);
        System.out.println(a.get(1));
    }
}
+2

HashMap<Integer, Double>. ,

myMap.put(currentMaximumIndex++, myDoubleValue);

That way the indexes would be unique, if you needed a sparse storage, you would be reasonably in order, and deleting the value would not hurt the existing ones.

+2
source

The addition to the above answer also suggested using LinkedHashMap<Integer,Double>instead of the usual hashmap. It will preserve the order in which you insert the element.

+1
source