0
class ExeTime {
public static void main (String[] args) {

    LinkedList<Integer> ll = new LinkedList<Integer>();
    ArrayList<Integer> al = new ArrayList<Integer>();

    addElement("LinkedList", ll);
    addElement("ArrayList", al);
}

static void addElement(String type, List listType){
    final long startTime = System.currentTimeMillis();

    for(int i = 0; i<= 1E5; i++){
        listType.add(i);
    }
    final long endTime = System.currentTimeMillis();
    final long timeTaken = endTime - startTime;
    System.out.println("Type:::: "+type+" ::timeTaken:: "+timeTaken);
}  }

Output for above piece of code is ::::

Type:::: LinkedList ::timeTaken:: 11

Type:::: ArrayList ::timeTaken:: 18

Now if I interchange the call for addElement method then I get the following output::::

Type:::: ArrayList ::timeTaken:: 10

Type:::: LinkedList ::timeTaken:: 16

I fail to understand why the sequence to add integer to a LinkedList and ArrayList change the execution time of the method. I tried the same for removing the elements and the results were OK. Could anyone please help me get to know as why this might be happening only while adding elements...

Sanket
  • 39
  • 1
  • 9

0 Answers0