在Java List和Queue中,两者都是作为对象的有序列表引入的,其中同一对象可能被添加多次。两者之间的区别在于添加元素的方式。在队列中,所有元素都插入到后面,然后从前面删除,而我们可以在列表中的任何位置添加元素。
| 序号 | 键 | 静态队列 | 单链表 |
|---|---|---|---|
| 1个 | 数据初始化。 | Static Queue works in first out(FIFO) fashion as all the elements get inserted at the REAR and removed from the FRONT of the queue. | 对于单链接列表,可以在列表中的任何位置添加元素,也可以基于列表中的索引获取任何元素。 |
| 2 | 内部实施。 | Internally queue has implemented array which makes it faster for searching and addition of elements. | 另一方面,列表维护节点和用于存储下一个节点的数据和地址的指针 |
| 3 | 尺寸 | Statis queue is fixed in size and could not be altered. The size of queue is defined at the time of its declaration. | 列表没有固定大小,因此在声明列表时不需要大小。 |
| 4 | 性能 | The static queue is faster in case of searching for an element while the deletion of an element is slower because deletion requires shifting of all the remaining elements to the front by one position. | 该列表由于其基于节点的实现而在搜索中较慢,但由于一个节点的唯一指针地址需要更新而不是在整个列表中进行更新,因此删除速度更快。 |
| 5 | 数据迁移。 | The static queue is always based on First in first out (FIFO) technique. | 另一方面,列表可以是FIFO或后进先出(LIFO)。 |
StaticQueueDemo.java
import java.util.*;
public class StaticQueueDemo {
public static void main(String args[]) {
PriorityQueue < String > queue = new PriorityQueue < String > ();
queue.add("Jack");
queue.add("Smith");
queue.add("John");
System.out.println("head:" + queue.element());
System.out.println("head:" + queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr = queue.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator < String > itr2 = queue.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}输出结果
head:Jack head:Jack iterating the queue elements: Jack Smith John after removing two elements: Smith
LinkedListDemo.java
import java.util.*;
public class LinkedListDemo {
public static void main(String[] args) {
// Creating a LinkedList
LinkedList < String > friends = new LinkedList <> ();
// Adding new elements to the end of the LinkedList using add() method.
friends.add("John");
friends.add("Jack");
friends.add("Smith");
friends.add("Chris");
System.out.println("Initial LinkedList : " + friends);
// Adding an element at the specified position in the LinkedList
friends.add(3, "Lisa");
System.out.println("After add(3, \"Lisa\") : " + friends);
}
}输出结果
Initial LinkedList : [John, Jack, Smith, Chris] After add(3,"Lisa") : [John, Jack, Smith, Chris, Lisa]