Explain the Collection interface in JAVA and its main implemented classes in detail

  • 2021-07-09 08:24:05
  • OfStack

Collection is the most basic set interface, and one Collection represents one set of Object, that is, the elements of Collection (Elements). Some Collection allow the same elements while others do not. One can sort while the other can't. Java SDK does not provide classes that directly inherit from Collection, Java SDK provides classes that inherit from "sub-interfaces" of Collection such as List and Set, Details can be found in the official document http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/Collection.html. Let's discuss the interfaces list and Set that inherit it. These two interfaces implement the main methods, but there are still some extensions. The iteration in list is different from that in collection, which will be described in detail below. Here we use an example to experience the implementation of the interface here:


Collection<Integer> list=new LinkedList<>(); 

list

list is an ordered collection (also known as a sequence). Users of this interface have precise control over where each element in the list is inserted. Users can access elements based on their integer index (position in the list) and search for elements in the list. list differs from Set in that list allows duplicate element insertions The list interface provides two efficient ways to insert and remove multiple elements anywhere in a list. Let's introduce the class of its implementation in detail under 1

LinkedList

It can be seen from the documentation that this listedList implements not only the list interface, but also the Deque interface, which provides FIFO queuing operations for add, poll, and other stack and double-ended queuing operations. The LinkedList here is implemented by double linked list, this class is not synchronous, so the external thread synchronization must be implemented when there are modifications to the elements in multiple threads

Construction method

LinkedList() Create an empty linked list LinkedList(Collection<? extends E> c) Construct a list containing the elements in the specified collection, arranged in the order returned by the iterator of its collection, as follows:

 ArrayList<Integer> arrayList=new ArrayList<>(); // New here 1 Linear list 
 LinkedList<Integer> linkedList=new LinkedList<Integer>(arrayList); // New with Linear List 1 Linked list 
 System.out.println(linkedList.getFirst()); 

Summary of Methods

boolean add(E e) Adds the specified element to the end of this list. Successful insertion returns True void add(int index, E element) Inserts the specified element at the specified position in this list. boolean addAll(Collection<? extends E> c) Adds all elements in the specified collection to the end of this list in the order in which the iterator specifying collection returns those elements. Examples are as follows:

ArrayList arrayList=new ArrayList();// New 1 Linear table 
 arrayList.add(10);
 arrayList.add(100);
 arrayList.add(2);
 LinkedList linkedList=new LinkedList();
 linkedList.add(100);
 linkedList.add("chenjiabing");

 linkedList.addAll(arrayList); // Add all the elements in the linear table to the linked list 
 for(Object i:linkedList)
 {
  System.out.println(i);
 }
boolean addAll(int index, Collection<? extends E> c) Inserts all elements in the specified collection into this list starting at the specified position. addFirst Adds the specified element to the beginning addLast Adds the specified element to the end clear() Remove all elements from the list clone() Get a copy of the linked list. Because the returned type is Object, it needs to be cast to LinkedList

LinkedList list=(LinkedList)linkedList.clone();
LinkedList(Collection<? extends E> c) 0 Returns True if this list contains element o element() Gets but does not remove the header (the first element) of this list. iterator() Returns an iterator for elements in a list

Iterator iter=list.iterator(); // Return 1 Iterator types 
while(iter.hasNext()) // Determine whether there are elements in the iterator 
{
 Object o=iter.next(); 
 if(o.equals(1))
 {
 System.out.println(o); // Output the elements in the iterator 
 iter.remove(); // Remove this element, which is directly removed from the list 
}

}
listIterator () returns list iterators (in the appropriate order) for the elements in this list, starting at the specified position in the list

ListIterator iterator = list.listIterator();
 while (iterator.hasNext()) // First, the iterator 1 Run straight to the end 
 {
  Object o = iterator.next();
  if (o.equals(1)) {
  iterator.add(100); // Inserts the element in front of the current element, which is in the Iterator Is a non-existent method 
  }

 }

 while (iterator.hasPrevious()) // The iterator in this case starts at the end, so it is equivalent to the output in reverse order here 
 {
  System.out.println(iterator.previous());
 }

get (int index) returns the element at the specified position in this list. It should be noted here that although this method can get the value of the specified index, the operation overhead in the linked list is very large here, so this method is not recommended. If you need to traverse the list, you can use iterators and for-each statements


LinkedList list=new LinkedList();
for(int i=0;i<10;i++)
{
 list.add(i);
}
for(Object o:list){ // Use for-each Traverse the list 
System.out.println(o); 
}

Iterator iter=list.iterator(); // Return 1 Iterator types 

while(iter.hasNext()) // Determine whether there are elements in the iterator 
{
 System.out.println(iter.next()); // Output the elements in the iterator 
}
getFirst () returns the first element of this list. getLast () returns the last 1 element of this list indexOf (Object o) returns the index of the first occurrence of an element lastIndexOf (Object o) returns the index of the last occurrence of an element toArray () returns an array containing all the elements in this list in the appropriate order, from the first element to the last element set (index, element) Replaces the element of the specified index with element size () returns the number of elements remove () removes the element from the header remove (index) removes the element at the specified position in this list.

ArrayList

List interface size variable array implementation. All optional list operations are implemented and all elements including null are allowed. In addition to implementing the List interface, this class also provides methods to manipulate the size of the array used internally to store the list. (This class is roughly equivalent to the Vector class, except that this class is out of sync.) Each ArrayList instance has 1 capacity. This capacity refers to the size of the array used to store list elements. It is always at least equal to the size of the list. As elements are added to ArrayList, its capacity automatically increases. The details of the growth strategy are not specified, because it is not as simple as adding elements and sharing fixed time overhead. Note that this implementation is not synchronous. If multiple threads access one instance of ArrayList at the same time and at least one of them modifies the list structurally, it must remain externally synchronized. (Structural modifications are any addition or deletion of one or more elements, or explicit resizing of the underlying array; Simply setting the value of an element is not a structural modification.) This is accomplished by synchronizing the objects that naturally encapsulate the list. If no such object exists, the list should be "wrapped" using the Collections. synchronizedList method

Constructor

ArrayList () constructs an empty list with an initial capacity of 10. ArrayList(Collection < ? extends E > c) constructs a list of elements of the specified collection, arranged in the order in which the iterators of the collection return them. Constructs an empty list with the specified initial capacity.

Summary of Methods

Because it inherits the same interface with LinkedList, most of the functions are the same, but it expands some unique methods, including add, addAll, get, clone, clear, contains, indexOf, remove, set, size, toArray, lastIndexOf, iterator and listIterator. The unique methods are as follows: isEmpty () returns true if there are no elements in this list void trimToSize () adjusts the capacity of this ArrayList instance to the current size of the list. Because the capacity of the linear list here increases with the elements added, this function changes the capacity of the linear list to the size of the elements

Vector

The Vector class implements a growable array of objects. Like Array 1, it contains components that can be accessed using integer indexes. However, the size of the Vector can be increased or decreased as needed to accommodate the addition or removal of items after the creation of the Vector Each vector attempts to optimize storage management by maintaining capacity and capacityIncrement. capacity should always be at least equal in size to the vector; This value is usually larger than the latter, because as the component is added to the vector, its storage will increase by the size of capacityIncrement. Applications can increase the capacity of vectors before inserting a large number of components; This reduces the amount of increased redistribution. It can be seen from the source code that Vector is thread-safe, and the insertion and deletion operations in the source code all realize the synchronous statement block of the process, so the insertion and deletion of Vector are relatively inefficient

Constructor

Vector () constructs an empty vector so that its internal data array has a size of 10 and its standard capacity increment is zero. Vector(Collection < ? extends E > c) constructs a vector that contains the elements in the specified collection, arranged in the order of the elements returned by their collection iterators. Vector (int initialCapacity) constructs an empty vector with the specified initial capacity and a capacity increment equal to zero. Vector (int initialCapacity, int capacityIncrement) constructs an empty vector with the specified initial capacity and capacity increment. Note: Using the first method, the system will automatically manage vectors, if using the latter two methods. The system will set the capacity of the vector object (that is, the size of data that can be stored by the vector object) according to the parameter, initialcapacity, when the number of data actually stored exceeds the capacity. The system will expand the storage capacity of vector objects.

Summary of Methods

It also inherits the List interface, so most of the methods are of the same kind, such as add, addAll, clear, clone, contains, remove and removeall

stack

The Stack class represents a last in first out (LIFO) object stack. It extends the class Vector with five operations, allowing vectors to be treated as stacks. It provides the usual push and pop operations, as well as the peek method for taking stack vertices, the empty method for testing whether the stack is empty, and the search method for looking up items in the stack and determining the distance to the top of the stack.
Note: Although stack here inherits Iterator interface, if iteration is used, it outputs the original order of your input, which violates the principle of stack. LIFO

Construction method

Stack () creates an empty stack.

Summary of Methods

isEmpty () tests whether the stack is empty. peek () looks at the object at the top of the stack, but does not remove it from the stack. pop () removes the object at the top of the stack and returns it as the value of this function. push (E element) pushes items onto the top of the stack. search (Object o) returns the position of the object on the stack, based on 1.

Related articles: