Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep List index fixed in Java

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.

like image 228
MhdSyrwan Avatar asked Dec 15 '11 22:12

MhdSyrwan


1 Answers

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 Collection
  • It stores values mapped to an ordered set of keys (similar to List'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.

like image 120
Egor Avatar answered Sep 19 '22 10:09

Egor