Java中的静态队列和单链接列表之间的区别。
在JavaList和Queue中,两者都是作为对象的有序列表引入的,其中同一对象可能被添加多次。两者之间的区别在于添加元素的方式。在队列中,所有元素都插入到后面,然后从前面删除,而我们可以在列表中的任何位置添加元素。
StaticQueueworksinfirstout(FIFO)fashionasalltheelementsgetinsertedattheREARandremovedfromtheFRONTofthequeue.
Internallyqueuehasimplementedarraywhichmakesitfasterforsearchingandadditionofelements.
Statisqueueisfixedinsizeandcouldnotbealtered.Thesizeofqueueisdefinedatthetimeofitsdeclaration.
Thestaticqueueisfasterincaseofsearchingforanelementwhilethedeletionofanelementisslowerbecausedeletionrequiresshiftingofalltheremainingelementstothefrontbyoneposition.
ThestaticqueueisalwaysbasedonFirstinfirstout(FIFO)technique.
静态队列和单链接列表示例。
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]