Joker
Joker

Reputation: 11150

How to put a element in specific location of array list

I want to add a element in specific location of array list For that i tried to initialize the array list with inital capacity.

import java.util.ArrayList;

 public class AddInArrayList{
  public static void main(String[] args) {
  ArrayList list = new ArrayList(4);
  Object obj1 = new Object();
   list.add(1, obj1);
  }
}

OUTPUT

Exception in thread "main" java.lang.IndexOutOfBoundsException:

Index: 1, Size: 0 at java.util.ArrayList.add(ArrayList.java:359) at AddInArrayList.main(AddInArrayList.java:7)

Is There any way to add a element by specific index location ?

Upvotes: 0

Views: 3257

Answers (4)

joki
joki

Reputation: 6879

You are confused about the meaning of capacity: the number you pass to the constructor does not set the inital list size.

You can't insert an element at index 1 of an empty list because list slots cannot be empty. If you wanted a function that expands the list before inserting at an index greater than its length, you could use:

static void addAtPos(List list, int index, Object o) {
    while (list.size() < index) {
        list.add(null);
    } 
    list.add(index, o);
}

That said, ArrayLists are based on arrays which do not perform well with mid-insertion. So a different data structure will almost certainly be better suited to your problem, but you'd have to let us know what you're trying to achieve.

Upvotes: 2

devops
devops

Reputation: 9197

initial capacity will be used only to set the initial "buffer" size of underlying array. so after calling new ArrayList(4) you list is still empty.

If you know your List will contain about 10_000 elements, create the ArrayList instance with intial capacity c = 10_000 + x. In this way you will avoid expensive ArrayList#grow(newcapacity) (Java 8) calls.

The method ArrayList#add(position, element) could be also called ArrayList#addAndMoveOtherToTheRight(position, element)

Upvotes: 0

Everv0id
Everv0id

Reputation: 1982

You're getting IndexOutOfBoundsException because when you call add(index, value), the value has to be not less than 0 and not bigger than list.size()-1. In your case it should be add(0, obj1).

Upvotes: 0

niyasc
niyasc

Reputation: 4490

Arrays will not let you to perform insertion at an index which is greater than array.size.

So if you want to associate each item with a number/index it is better to use maps.

Map map = new HashMap<Integer, Object>();

Object obj1 = new Object();

map.put(1, obj1);

Upvotes: 0

Related Questions