Java Collection Series (II)

Keywords: Java JDK

Preface

Through the introduction of the last Java Collection Series (1), readers must have mastered the basic concepts of collections. Next, the author will focus on the functions of each interface of collections and its common subclasses.

Definition of Collecton Interface

The Collection interface is defined as follows:

public inteface Collection<E> extends Iterable

It can be found from the definition of interface that generic definition is used in this interface, and specific operation type must be specified in operation. This ensures the security of collection operations and avoids ClassCastException exceptions.

Little knowledge points

Generic support was added after JDK 1.5 to ensure that all elements in the collection are of the same type.

Collection interface is the largest parent interface for single-valued storage, in which multiple single-valued (single object) data can be stored.

Note: In general development, Collection interface is seldom used directly, and its sub-interface is basically used. The main sub-interfaces are List, Set, Queue and SortedSet.

Definition of Collection Subinterface

List: Can store duplicate content
Set: You can't store duplicates. All duplicates are distinguished by hashCode() and equals().
Queue: Queue interface
SortedSet: You can sort the data in the collection.

List interface

Definition of List Interface

List is the sub-interface of Collection, where you can save each duplicate content. This interface is defined as follows:`

public interface List<E> extends Collection<E>`

Common subclasses of List interfaces

New subclass: ArrayList

ArrayList is a List subclass that can be instantiated directly for the List interface through the polymorphism of objects. Definition of this kind

public  class ArrayList<E> extends AbstractList<E>
implements List<E>,RandomAccess,Cloneable,Serializable 

From the definition, it can be found that the ArrayList class inherits the AbstractList class. The AbstractList class is defined as follows:

public abstract class Abstract<E> extends AbstractCollection<E> implements List<E> 

This class implements the List interface, so you can instantiate the List interface directly using ArrayList.

Operation 1: Increase data

Code demonstration

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ArrayListDemo01{
public static void main(String[] args){
List<String> allList=null; //Define List Objects
Collection<String> allCollection=null;//Define Collection Objects
allList=new ArrayList<String>(); //Instantiating List objects can only be String types
allCollection=new ArrayList<String>();//Instantiating Collection objects can only be String types
allList.add("Hello"); //Inheritance from Collection
allList.add(0,"world");//This method extends List
System.out.println(allList);//Contents in the output set
allCollection.add("LJZ");//Add data
allCollection.add("www.baidu.com");//Add data
allList.addAll(allCollection); //Increase a set of objects by inheriting from Collection
allList.addAll(0,allCollection);//This method is customized by List, adding a set of objects
System.out.println(allList);//Output object, calling toString () method
   }
}

Program output results:

[world, Hello]
[LJZ, www.baidu.com, world, Hello, LJZ, www.baidu.com]

From the running results of the program, it can be found that adding elements in the set can be done at the specified location by using the add(int index,E element) method in List, while the other two add() methods only add content at the end of the set.

Operation 2: Delete objects

import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo02{
public static void main(String[] args){
List<String> allList=null; //Declare List objects
allList=new ArrayList<String>()//Instantiating List objects can only be String types
allList.add("Hello");//Add elements
allList.add(0,"world"); //Adding elements at specified locations
allList.add(1,"LJZ");  //Adding elements at specified locations
allList.remove(1);  //Delete elements at specified locations
allList.remove("world");  //Delete elements of specified content
System.out.println(allList); //Output object, calling toString() method
  }
}  

Running results: [Hello]

Operation 3: Output the contents of List

In the Collection interface, the method size() is defined to get all the data length, while in the List interface, there is an operation get (int index) to get the specified location elements in the collection, which can output all the contents of the collection.

import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo03{
public static void main(String[] args){
List<String> allList=null;  //Define List Interface Objects
allList=new ArrayList<String>(); //Instantiating List objects can only be String types
allList.add("Hello");
allList.add('L');
allList.add('J');
allList.add('Z');
allList.add(0,"Hello");
allList.add(1,"world");
System.out.print("Output from front to back");
for(int i=0;i<allList.size();i++){
System.out.print(allList.get(i)+",");
}
System.out.print("\n Output from back to front");
for(int i=allList.size();i>=0;i--){
System.out.print(allList.get(i)+",");
  }
 }
}

The results of program operation are as follows:

Output Hello,world,Hello,L,J,Z from front to back.
Output Z,J,L,Hello,world,Hello from back to front.

From the running results of the program, we can see that the order of data increase in List collection is the order after output, and the order itself will not change.

Operations 4: Turn a collection into an array of objects

import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo04{
public static void main(String[] args){
List<String> allList=null;
allList=new ArrayList<String>();
allList.add("A");
allList.add("B");
allList.add("C");
allList.add(0,"D");
allList.add(4,"E");
String str[]=allList.toArray(new String[]{});
System.out.print("Specifies the array type:");
for(int i=0;i<str.length;i++ ){
System.out.print(str[i]+",");
}
System.out.print("\n Returns an array of objects:");
Object obj[]=allList.toArray();
for(int i=0;i<obj.length;i++){
String temp=(String)obj[i];
System.out.print(temp+",");
  }
 }
}   

The results of program operation are as follows:

Specify array types: D,A,B,C,E,
Returns an array of objects: D,A,B,C,E,

Operations 5: Intercept the set, find the location of the element, determine whether the element exists, whether the set is empty, and so on.

import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo05{
public static void main(String[] args){
List<String> allList=null;
allList=new ArrayList<String>();
System.out.print("Is the collection empty before operation?"+allList.isEmpty());
allList.add("A");
allList.add("B");
allList.add("C");
allList.add("D");
System.out.println(allList.contains("Hello")?"\"Hello\"String exists!":"\"Hello\"String does not exist!");
List<String> allSub= allList.subList(1,2);
System.out.print("Collection interception:");
for(int i=0;i<allSub.size();i++){
System.out.print(allList.get(i)+",");
}
System.out.println("");
System.out.println("C Character position"+allList.indexOf("C"));
System.out.println("Is the collection empty after operation?"+allList.isEmpty());
}
}

The results of program operation are as follows:

Is the collection empty before operation? The true "Hello" string does not exist!
Collection interception: A,
C character position 2
Is the collection empty after operation? false

Save the subclass: Vector

> There is also a subclass Vector in the List interface. Vector class belongs to a rescued subclass. From the history of Java collections, Vector is an old-fashioned class, which existed in JDK 1.0. After Java 2, the concept of aggregate framework was emphasized, so many new interfaces (such as List) were defined successively. However, considering that a large number of users are used to using Vector classes, Java designers let Vector classes implement an additional List interface, which is retained. But because it is a subclass of List, the use of Vector classes is not very different from the previous one.

The above two classes are compared simply, but from the point of view of practical application development, ArrayList class is used more, and readers should focus on it.

LinkedList Subclass and Queue Interface

LinkedList represents an operation class of linked list, that is, Java has provided a linked list program for developers to use directly without redevelopment. The LinkedList class is defined as follows:

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>,Queue<E>,Cloneable,Serializable      

It is easy to see from the definition that although this class implements the List interface, it also implements the Queue interface, so it can call the method defined by the Queue interface.

Operation 1: Adding data to the linked list

package ljz;
import java.util.LinkedList;
public class LinkedListDemo01{
public static void main(String[] args){
LinkedList<String> link=new LinkedList<String>();
link.add("A");
link.add("B");
link.add("C");
link.add("D");
System.out.println("Initialize the list:"+link);
link.addFirst("X");
link.addLast("Y");
System.out.println("Add the list after the head and tail:"+link);
}
}

The results of program operation are as follows:

Initialization list: [A, B, C, D]
Add the list after the head and tail: [X, A, B, C, D, Y]

Operation 2: Find the list head

  • Find the header: public E peek()
  • Find a table header that does not delete: public E peek()
  • Find and delete the header: public E poll()
import java.util.LinkedList;
public class LinkedListDemo02{
public static void main(String[] args){
LinkedList<String> link=new LinkedList<String>();
link.add("A");
link.add("B");
link.add("C");
link.add("D");
System.out.println("1,element()Method Find the header:"+link.element());
System.out.println("2,Find the linked list content" +link);
System.out.println("3.peek()Method to find the header" +link.peek());
System.out.println("4.Find the following list content:"+link);
Ststem.out.println("5.poll()Method to find the header"+link.poll());
System.out.println("6.Find the following list content:"+link);
 }
} 

The results of program operation are as follows:

1. The element () method finds the header: A
2. Find the linked list content [A, B, C, D]
3.peek() method finds header A
4. Find the following list content: [A, B, C, D]
5. The poll () method finds the header A
6. Find the link list content: [B, C, D]

Operation 3: Take out all data in a first-in-first-out manner

There is a poll() method in the LinkedList class. By looping through this operation, you can extract all the content (in FIFO mode).

package ljz;
import java.util.LinkedList;
public class LinkedListDemo03 {
    public static void main(String[] args){
    LinkedList<String> link=new LinkedList<String>();
    link.add("A");
    link.add("B");
    link.add("C");
    link.add("D");
    System.out.print("with FIFO Mode output:");
    for(int i=0;i<link.size()+1;i++){
    System.out.print(link.poll());  
    }

    }

}

Program output results:

Output in FIFO: ABC

In the next article, I'll introduce Set, SortedSet, the basic concepts and usage of set output.

Posted by first_lady_the_queen on Tue, 21 May 2019 11:45:49 -0700