Use of JAVA LinkedList & Difference between Java pop and poll

Links to the original text: https://blog.csdn.net/I_peter/article/details/50999720

First, we conclude that pop and poll are the first elements of LinkedList and delete them, which is equivalent to removeFirst.
Differences: the data structures used in the implementation of the two are different.

  • poll is a method based on queue structure. When there are no elements in the queue, this method is called to return null.
  • pop is a method based on stack structure. When there are no elements in the stack, calling this method will cause an exception.

ArrayList: The underlying implementation is an array with a default length of 10

LinkedList: The underlying implementation is a linked list

Demo of LinkedList:

LinkedList<String> list = new LinkedList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
System.out.println(list);// [A, B, C, D]
// Adding elements to the tail
list.addLast("E");
System.out.println(list);// [A, B, C, D, E]
// Adding elements to the head
list.addFirst("a");
System.out.println(list);// [a, A, B, C, D, E]
// Adding elements to the head
list.push("66");
System.out.println(list);//[66, a, A, B, C, D, E]


// Capturing and removing head elements
list.removeFirst();
System.out.println(list);//[a, A, B, C, D, E]

// Adding data at specified locations
list.add(3, "b");  
System.out.println(list);// [a, A, B, b, C, D, E]
// poll uses the method to get and delete the first element of the list
String str1 = list.poll();
System.out.println(str1 + "##" + list);// a##[A, B, b, C, D, E]

// peek uses the method to get the first element of the list that is not deleted
String str2 = list.peek();
System.out.println(str2 + "##" + list);// A##[A, B, b, C, D, E]
// pop fetches the elements from the stack and exits the stack
String str3 = list.pop();
System.out.println(str3 + "##" + list);// A##[B, b, C, D, E]



//Linkedlist and Array Conversion
String arrstr[]=new String[list.size()];
list.toArray(arrstr);
for(String str:arrstr){
    System.out.print(str+"\t");//B    b    C    D    E

}
//************************
//The second method of constructing linkedList
LinkedList<String> list2 = new LinkedList<String>(list);
System.out.println("\n The second method of construction is:"+list2);//The second construction method: [B, b, C, D, E]

 

Posted by castis on Tue, 08 Oct 2019 16:47:17 -0700