数组是存储在连续内存位置的项目的集合。这个想法是将多个相同类型的项目存储在一起。但是,数组的局限性在于数组的大小是预定义和固定的。有多种方法可以解决这个问题。在本文中,讨论了为解决此问题而实现的两个类ArrayList和LinkedList之间的区别。
数组列表
ArrayList 是集合框架的一部分。它存在于Java.util包中,并在Java为我们提供动态数组。虽然,它可能比标准数组慢,但在需要对数组进行大量操作的程序中很有帮助。我们可以动态添加和删除项目。它会自动调整大小。下面通过一个例子来演示ArrayList的实现。
// Java program to demonstrate the
// working of an ArrayList
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Declaring an ArrayList
ArrayList arrli
= new ArrayList();
// Appending the new elements
// at the end of the list
for (int i = 1; i <= 5; i++)
arrli.add(i);
// Printing the ArrayList
System.out.println(arrli);
// Removing an element from the
// List
arrli.remove(3);
// Printing the ArrayList after
// removing the element
System.out.println(arrli);
}
}
输出:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
链表
此类实现LinkedList 数据结构。链表是线性数据结构,其中元素不存储在连续位置,每个元素都是一个单独的对象,具有数据部分和地址部分。这些元素使用指针和地址链接。每个元素称为一个节点。由于插入和删除的动态性和易用性,它们比数组更受欢迎。下面通过一个例子来演示LinkedList的实现。
// Java program to demonstrate the
// working of a LinkedList
import java.util.*;
public class Test {
public static void main(String args[])
{
// Creating an object of the
// class linked list
LinkedList object
= new LinkedList();
// Adding the elements to the
// linked list
object.add("A");
object.add("B");
object.addLast("C");
System.out.println(object);
// Removing elements from the
// list
object.remove("B");
object.removeFirst();
System.out.println("Linked list after "
+ "deletion: " + object);
}
}
输出:
[A, B, C]
Linked list after deletion: [C]
JavaArrayList和LinkedList的区别
ArrayList | LinkedList |
---|---|
This class uses a dynamic array to store the elements in it. With the introduction of generics, this class supports the storage of all types of objects. | This class uses a doubly linked list to store the elements in it. Similar to the ArrayList, this class also supports the storage of all types of objects. |
Manipulating ArrayList takes more time due to the internal implementation. Whenever we remove an element, internally, the array is traversed and the memory bits are shifted. | Manipulating LinkedList takes less time compared to ArrayList because, in a doubly-linked list, there is no concept of shifting the memory bits. The list is traversed and the reference link is changed. |
This class implements a List interface. Therefore, this acts as a list. | This class implements both the List interface and the Deque interface. Therefore, it can act as a list and a deque. |
This class works better when the application demands storing the data and accessing it. | This class works better when the application demands manipulation of the stored data. |