[Data Structure]Q2:Differences between ArrayList and LinkedList .

ArrayList is based on a dynamic array, which allows for fast random access but slower insertions and deletions. On the other hand, LinkedList is based on a linked list, which enables efficient insertions and deletions but slower random access.

ArrayList provides constant time complexity O(1) for accessing elements by index since it internally uses an array. This makes it suitable for scenarios where random access is frequent, such as retrieving elements by index or iterating over the list. However, inserting or deleting elements in the middle of an ArrayList requires shifting the subsequent elements, resulting in a time complexity of O(n).

LinkedList, on the other hand, has constant time complexity O(1) for inserting or deleting elements at the beginning or end of the list since it only requires updating the references. This makes LinkedList suitable for scenarios where frequent insertions or deletions are needed, such as implementing a queue or a stack. However, accessing elements by index in a LinkedList requires traversing the list from the beginning or end, resulting in a time complexity of O(n)(需要从头到尾遍历列表,导致时间复杂度为O(n)).

To illustrate the differences, consider the following code examples. First, let's create an ArrayList:

import java.util.ArrayList;

ArrayList<Integer> arrayList = new ArrayList<>();

arrayList.add(10);  // Appends 10 at the end of the list
arrayList.add(20);  // Appends 20 at the end of the list
arrayList.add(30);  // Appends 30 at the end of the list

int elementAtIndex1 = arrayList.get(1);  // Retrieves the element at index 1 (20)
arrayList.remove(0);  // Removes the element at index 0 (10)

System.out.println(arrayList);  // Output: [20, 30]

Next, let's create a LinkedList:

import java.util.LinkedList;

LinkedList<Integer> linkedList = new LinkedList<>();

linkedList.add(10);  // Appends 10 at the end of the list
linkedList.add(20);  // Appends 20 at the end of the list
linkedList.add(30);  // Appends 30 at the end of the list

int elementAtIndex1 = linkedList.get(1);  // Retrieves the element at index 1 (20)
linkedList.remove(0);  // Removes the element at index 0 (10)

System.out.println(linkedList);  // Output: [20, 30]

In both examples, we add elements to the list, retrieve an element by index, and remove an element by index. The output in both cases is [20, 30]. However, the underlying implementation and the performance characteristics of these operations differ between ArrayList and LinkedList.

How to add and delete at the beginning for the arraylist?

Adding and deleting elements at the beginning of an ArrayList can be less efficient compared to LinkedList because it requires shifting all the existing elements. However, you can still achieve it using the following approaches:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();

        // Adding elements at the beginning of the ArrayList
        arrayList.add(0, "Element 1");
        arrayList.add(0, "Element 2");
        arrayList.add(0, "Element 3");

        System.out.println("ArrayList after adding at the beginning: " + arrayList);

        // Deleting the first element from the ArrayList
        String removedElement = arrayList.remove(0);

        System.out.println("Removed element: " + removedElement);
        System.out.println("ArrayList after deleting from the beginning: " + arrayList);
    }
}

Output:

ArrayList after adding at the beginning: [Element 3, Element 2, Element 1]
Removed element: Element 3
ArrayList after deleting from the beginning: [Element 2, Element 1]

 

How to add and delete at the beginning for the linkedlist?

To add an element at the beginning of a LinkedList, you can use the addFirst() method. To delete the first element from the LinkedList, you can use the removeFirst() method. Here's an example code snippet demonstrating how to add and delete elements at the beginning of a LinkedList in Java:

import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();

        // Adding elements at the beginning of the LinkedList
        linkedList.addFirst("Element 1");
        linkedList.addFirst("Element 2");
        linkedList.addFirst("Element 3");

        System.out.println("LinkedList after adding at the beginning: " + linkedList);

        // Deleting the first element from the LinkedList
        String removedElement = linkedList.removeFirst();

        System.out.println("Removed element: " + removedElement);
        System.out.println("LinkedList after deleting from the beginning: " + linkedList);
    }
}
LinkedList after adding at the beginning: [Element 3, Element 2, Element 1]
Removed element: Element 3
LinkedList after deleting from the beginning: [Element 2, Element 1]

Let's dive into a more concrete explanation of why ArrayList and LinkedList have the mentioned features and time complexities.

ArrayList:

  • ArrayList internally uses an array to store its elements. The array has a fixed size, but ArrayList automatically handles resizing the array when necessary. When the ArrayList is created, it typically starts with a default initial capacity. As elements are added, if the array becomes full, ArrayList creates a new array with a larger capacity and copies the existing elements to the new array. This resizing process allows ArrayList to dynamically grow and accommodate additional elements.
  • Accessing elements by index in an ArrayList is fast and has a constant time complexity of O(1). Since ArrayList uses an array, accessing an element at a specific index is as simple as performing an array index lookup, which is a direct memory access operation.
  • However, inserting or deleting elements in the middle of an ArrayList is less efficient. When an element is inserted or deleted at a specific index, it requires shifting the subsequent elements to accommodate the change. This shifting operation has a time complexity of O(n), as it needs to move n - 1 elements (where n is the number of elements) in the worst case. The larger the ArrayList, the more elements need to be shifted, making this operation slower compared to inserting or deleting elements at the beginning or end.

LinkedList:

  • LinkedList internally uses a doubly linked list(双链表) data structure. Each node in the list contains the element itself and references to the previous and next nodes in the list. This structure allows for efficient insertions and deletions at the beginning or end of the list.
  • Inserting or deleting an element at the beginning or end of a LinkedList has a constant time complexity of O(1). This is because it only requires updating the references of the affected nodes. For example, when inserting an element at the beginning, a new node is created, its next reference is set to the current first node, and the previous reference of the current first node is set to the new node.
  • However, accessing elements by index in a LinkedList is slower. To access an element at a specific index, the LinkedList needs to traverse the list from either the beginning or the end until reaching the desired index. This traversal operation has a time complexity of O(n), as it may require iterating through all the nodes in the list. The further the index is from the start or end, the more nodes need to be traversed, making this operation slower compared to ArrayList's random access.
  • In case this is still not that understandable, here is another reply with vivid language:

Imagine you have a group of friends standing in a line, where each person holds hands with the person next to them. This represents a LinkedList. Each person represents a node, and the hand-holding represents the references to the previous and next nodes.

To insert or remove a person at the beginning or end of the line, you can simply ask someone to join or leave the line by holding or releasing hands. This process is quick because it only involves updating the references of the affected individuals. For example, if someone new wants to join at the beginning, they can hold the hand of the first person in line, while the first person's previous reference now points to the new person. This way, the new person is seamlessly inserted at the beginning.

However, if you want to find a specific person in the line, let's say the third person, you would need to start from the beginning of the line and count each person until you reach the desired position. This counting process takes more time, especially if the person you're looking for is far from the beginning or end of the line.

In contrast, imagine another scenario where you have a group of friends standing in a row without holding hands. This represents an ArrayList. Each person represents an element, and their position in the row represents their index.

To insert or remove a person in the middle of the row, you would need to physically move everyone behind them to accommodate the change. For example, if you want to insert a person at the third position, you would need to shift all the people from the third position and beyond to make room. This process takes more time and effort, especially if the row is long and there are many people to shift.

However, if you want to find a specific person at a known index, you can directly look at that position in the row without the need to count or shift anyone. This direct access allows you to quickly find the person you're looking for.

In summary, the underlying data structures and the operations performed on them determine the performance characteristics of ArrayList and LinkedList. ArrayList's array-based implementation provides efficient random access but slower insertions/deletions in the middle, while LinkedList's linked list structure enables fast insertions/deletions at the beginning/end but slower random access. Choosing between them depends on the specific requirements of your application.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值