InterviewSolution
Saved Bookmarks
| 1. |
Where to use ArrayList and where to use LinkedList? |
|
Answer» In your program, if you try to insert the elements and retrieve the elements in the same order, then you should use LinkedList. Complexity for inserting an element is O(n) in case of LinkedList. If you don't NEED to MAINTAIN the insertion or deletion order, then you can use ArrayList. Also, the complexity of insertion and deletion in an ArrayList is O(1) as this data structure is indexed. An element can directly be accessed in ArrayList using index. Code Snippet: Insertion in an ArrayList can be DONE in 2 ways: add(E e) => Which appends the element at the end of the list. add(int index, E e) => Add the element at the specified position in the list ArrayList<String> arrayList = new ArrayList<String>(); arrayList .add("Programming"); arrayList .add(1, "Java"); arrayList .add("PYTHON"); arrayList .remove(1); // Remove value at index 1, considering the indexing starts from 0Insertion/ deletion in LinkedList: LinkedList linkedListObj = new LinkedList(); linkedListObj.add("Artificial Intelligence"); linkedListObj.add("Blocked Chain"); linkedListObj.add("ACADEMIC"); linkedListObj.remove("Blocked Chain"); |
|