DreamsCoder.com

We Code your Dreams


home > Difference between ArrayList and LinkedList in Java with example




Difference between ArrayList and LinkedList in Java with example







  • For frequent addition and deletion LinkedList is a best choice.
  • If there are more search operations then ArrayList would be a best solution.
  • ArrayList has direct references to every element in the list, so it can get the n-th element in constant time.
  • LinkedList has to traverse the list from the beginning to get to the n-th element.
  • Array List LinkedList
    get() O(1) O(n)
    add() O(1) O(1) amortized
    remove() O(n) O(n)


    /* LINKEDLIST EXAMPLE */
    	LinkedList ll = new LinkedList();
      
          ll.add("Dreams");
          ll.add("Coder");
          ll.add(".com");
          ll.addLast("Programming");
          ll.addFirst("www.");
          System.out.println("Original contents of ll:"+ll);
    
          // remove elements from the linked list
          ll.remove(".com");
          ll.remove(1);
          System.out.println("Contents of Linked List 
    ll after deletion: "+ ll);
          
          // remove first and last elements
          ll.removeFirst();
          ll.removeLast();
          System.out.println("Contents of Linked List 
    ll after deleting first and last: "+ ll);
    
    /* ARRAYLIST EXAMPLE */
         ArrayList arrlist = new
     ArrayList(5);
    
       arrylist.add(1);
       arrylist.add(2);
       arrylist.add(3);
       arrylist.add(4);
    
       for (Integer num : arrylist) {
       System.out.println("Number = " + number);
       } 
    	
       // retrieves element at 3rd postion
       int third =arrylist.get(2);
       System.out.println("Retrieved element is = " +third);
    }

    Label - java





    by - Chinmay Mahajan





    Are you looking for something else?


    Suggested Programs




    AES Encryption and Decryption using Java


    Dynamically Updating a List in JAVA


    Upload and Preview Image using JFrame in Java


    Connect Database and Retrieve values using JSP


    Chat application using Socket programming in JAVA