📜  ArrayList和LinkedList之间的区别

📅  最后修改于: 2020-10-12 09:38:44             🧑  作者: Mango

ArrayList和LinkedList之间的区别

ArrayList和LinkedList都实现List接口并维护插入顺序。两者都是非同步类。

但是,下面给出的ArrayList和LinkedList类之间有很多区别。

ArrayList LinkedList
1) ArrayList internally uses a dynamic array to store the elements. LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Java中ArrayList和LinkedList的示例

让我们看一个简单的示例,其中我们同时使用ArrayList和LinkedList。

import java.util.*;  
class TestArrayLinked{  
 public static void main(String args[]){  
   
  List al=new ArrayList();//creating arraylist  
  al.add("Ravi");//adding object in arraylist  
  al.add("Vijay");  
  al.add("Ravi");  
  al.add("Ajay");  
  
  List al2=new LinkedList();//creating linkedlist  
  al2.add("James");//adding object in linkedlist  
  al2.add("Serena");  
  al2.add("Swati");  
  al2.add("Junaid");  
  
  System.out.println("arraylist: "+al);
  System.out.println("linkedlist: "+al2);
 }  
}  

输出:

arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]