Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items to empty List at specific locations in java

Tags:

java

Is there any way I can make the below code work without commenting the 3rd line.

    List<Integer> list = new ArrayList<Integer>();
    list.add(0,0);
    //list.add(1,null);
    list.add(2,2);

I want to add items to list at specific locations. But if I don't change the index to Nth position I am not being able to add at Nth as told in this answer.

I can't use a map because I don't want to miss a value when the keys are same. Also adding null values to a list for large lists will be an overhead. When there is a collision I want the item to take the next position(nearest to where it should have been).

Is there any List implementation that shifts index before it tries to add the item?

like image 371
ManuPK Avatar asked Aug 11 '26 14:08

ManuPK


1 Answers

Use something like a MultiMap if your only concern is not "missing a value" if the keys are the same.

I'm not sure how doing a shift/insert helps if I understand your problem statement--if the "key" is the index, inserting will lose the same information.

like image 98
Dave Newton Avatar answered Aug 13 '26 05:08

Dave Newton