Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element in an ArrayList efficiently at a given index in java

I need to insert a element of type Person (my own defined class) in an ArrayList at index i

I know I can use add(int index, E element).

But is there any efficient method to do this as in my list it is taking around 1.5 ms on an average (data collected over 1000 insertion and then average).

like image 564
learner Avatar asked Jun 17 '13 11:06

learner


People also ask

How do you add an element to an ArrayList at a specific index?

The java. util. ArrayList. add(int index, E elemen) method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).

How do you add elements to an ArrayList dynamically in Java?

Since the size of an array is fixed you cannot add elements to it dynamically. But, if you still want to do it then, Convert the array to ArrayList object. Add the required element to the array list.

How do I add an element to a specific index?

add() method is used to add an element at particular index in Java ArrayList.


1 Answers

If your task is more insertion / deletion intensive, you can always use java.util.LinkedList.

  • ArrayList has a limited size. Every time you add an element, Java ensures that it can fit - so it grows the ArrayList. If the ArrayList grows faster, there will be a lot of array copying taking place.
  • LinkedList just adds the element to the correct place (linking the nodes around), without growing and copying of the whole ArrayList.
  • Drawbacks of the LinkedList are when you are searching for an element. Since it has no indexes, it must traverse from the beginning to the end of the list to find an item.

For LinkedList:

  • get is O(n)
  • add is O(1)
  • remove is O(n)
  • Iterator.remove is O(1)

For ArrayList:

  • get is O(1)
  • add is O(1) amortized, but O(n) worst-case since the array must be resized and copied
  • remove is O(n)
like image 186
darijan Avatar answered Nov 10 '22 00:11

darijan