The Collection Collection

  • public interface Collection<E>
    extends Iterable<E>
    Copy the code

    The root interface in the collection hierarchy. A collection represents a group of objects called its elements. Some collections allow repeating elements, while others do not. Some are ordered and others disordered. The JDK does not provide any direct implementation of this interface: it provides implementations of more specific subinterfaces, such as Set and List. This interface is typically used to pass collections around and manipulate them where maximum versatility is required.

    Packages or multiple sets (unordered collections that may contain repeating elements) should implement this interface directly.

    All generic Collection implementation classes (typically implementing 88446144404803 indirectly through their subinterfaces) should provide two “standard” constructors: A void (no arguments) constructor, which creates an empty Collection, and a constructor, Collection, which creates a new Collection of elements identical to its arguments. In fact, the latter constructor allows the user to copy any collection, generating an equivalent collection of the desired implementation type. There is no way to enforce this convention (because the interface cannot contain constructors), but rather a common Collection implementation in all Java platform libraries.

Collection Overview

  • Is the top-level interface to a singleton collection, which represents groups of objects, also known as elements of a C ollection
  • The JDK does not provide any direct implementation of this interface; it provides more specific subinterfaces (such as Set and List)

Implements an object that creates a Collection

  • Polymorphic way
  • The concrete implementation class ArrayList

Example:

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo {
    public static void main(String[] args) {
        // Create an object for the collection
        Collection<String> c = new ArrayList<String>();

        // Add element: Boolean add(E E)
        c.add("hi");
        c.add("good");
        c.add("morning");

        // Outputs the collection objectSystem.out.println(c); }}Copy the code

Effect:

 

Collection Common methods of Collection

The method name instructions
boolean add(E e) Add elements
boolean remove(Object o) Removes the specified element from the collection
void clear() Clears the elements in the collection
boolean contains(Object o) Checks whether the specified element exists in the collection
boolean isEmpty() Determines whether the set is empty
int size() The length of the set, the number of elements in the set

Example:

public class CollectionDemo {
    public static void main(String[] args) {
        // Create an object for the collection
        Collection<String> c = new ArrayList<String>();

        // Add element: Boolean add(E E)
        c.add("hi");
        c.add("good");
        c.add("morning");
        // Remove the element
        c.remove("good");
        // Empty the collection elements
// c.clear();
        // Check whether the set has the specified element
        System.out.println(c.contains("hi"));
        // Check whether the set is empty
        System.out.println(c.isEmpty());
        // The length of the output set
        System.out.println(c.size());

        // Outputs the collection objectSystem.out.println(c); }}Copy the code

Results:

View the source shortcut key

Shortcut keys: CTRL + the left mouse button to quickly view the source code

Shortcut key: Alt + 7 opens a window to see all the information about the class

Such as the Arraylist class

Iterator A collection Iterator

Iterator<E> Iterator (): Returns an Iterator of the elements in this collection, obtained from the collection’s Iterator () method

It can be used to traverse collections

public class CollectionDemo {
    public static void main(String[] args) {
        // Create an object for the collection
        Collection<String> c = new ArrayList<String>();

        // Add element: Boolean add(E E)
        c.add("hi");
        c.add("good");
        c.add("morning");

        //Iterator
      
        Iterator (): Returns an Iterator of the elements in this collection, obtained from the collection's Iterator () method
      
        Iterator it = c.iterator();
        // Check whether the next number in the set exists
        while(it.hasNext()){ System.out.println(it.next()); }}}Copy the code

Example: Store student objects and iterate over them

public class Student {
    private String name;
    private int age;

    public Student(a) {}public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age; }}Copy the code
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CollectionDemo {
    public static void main(String[] args) {
        // Prepare a student class

        // Create an object for the collection
        Collection<Student> students = new ArrayList<Student>();

        // Add element: Boolean add(E E)
        Student s1 = new Student("Cao cao".18);
        Student s2 = new Student("Liu bei".23);
        Student s3 = new Student("Lombardi".21);
        students.add(s1);
        students.add(s2);
        students.add(s3);

        / / the iterator
        Iterator<Student> it = students.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + ":"+ s.getAge()); }}}Copy the code

Results:

 

The List collection

  • public interface List<E>
    extends Collection<E>
    Copy the code

    Ordered sets (also known as sequences). The user of this interface can control exactly where each element in the list is inserted. Users can access elements through integer indexes (positions in the list) and search for elements in the list.

    Unlike collections, lists generally allow repeating elements. More formally, lists generally allow elements E1 and e2 to pair e1.equals(e2), and if they allow empty elements, they usually allow multiple empty elements. One might wish to implement a no-repeat list that throws a runtime exception when a user tries to insert, but we expect this use to be rare.

    The List interface places additional conventions over and above the iterator, Add, remove, equals, and hashCode method contracts on the Collection specified interface. Declarations of other inheritance methods are also included here for convenience.

    The List interface provides four positional (indexed) ways to access List elements. Lists (such as Java arrays) are zero. Note that these operations may be performed in conjunction with some implemented index values, such as the LinkedList class. Therefore, iterating through elements in the list usually takes precedence over indexes if the caller is unaware of the implementation.

    The List interface provides a special Iterator, called a ListIterator, that allows element insertion and replacement, and provides bidirectional access to normal operations in addition to the Iterator interface. Provides a way to get a list iterator starting at a specified position in a list.

    The List interface provides two ways to efficiently insert and delete multiple elements at any point in a List.

List collection overview

  • Ordered collections (also known as sequences) allow the user to control exactly where each element in the list is inserted. The donkey can be accessed through integer index | elements, and search for the elements in the list
  • Unlike sets, lists generally allow repeating elements

List collection features

  • Order: The order in which elements are stored and retrieved
  • Repeatable: Stored elements can be repeated
  • List inherits from the Collection

 

Enhanced for loop

Enhanced for: Simplifies traversal of arrays and collections

  • Implementing the Iterable interface allows its objects to be the target of enhanced for statements
  • It comes after JDK5, and inside is an Iterator

Enhance the format of for

For (element datatype variable name: array or Collection) {// Use the variable here that is, the quantity is the element}Copy the code

Example:

int[] arr = {1.2.3.4.5};
for(int i:arr){
    System.out.println(i);
}
Copy the code

 

List Indicates the collection subclass characteristics

The underlying implementation of ArryList is an array, which is fast to query, slow to add and delete

  • Described in theArrayTypeA class isOpen typeClass, and the examples describe the actionsOpen dataValues of n – dimensional array allOpen thethedataValue.

The underlying implementation of LinkedList is a LinkedList, which is slow to query and fast to add and delete

  • Doubly linked lists implement the List and Deque interfaces. Implement all optional list operations and allow all elements (including NULL).

    All operations can be expected like a two-way list. Index to list operations traverse the list from the beginning or the end, whichever is closer to the specified index.

 

The LinkedList collection has unique features

Collection specific functionality

The method name instructions
public void addFirst(E e) Inserts the specified element at the beginning of the list
public void addLast(E e) Appends the specified element to the end of this list
public E getFirst() Returns the first element in this list
public E getLast() Returns the last element in this list
public E removeFirst() Removes and returns the first element from this list
public E removeLast() Removes and returns the last element from this list

Example:

import java.util.LinkedList;

public class ListDemo {
    public static void main(String[] args) {
        // Create a collection object
        LinkedList<String> linkedList = new LinkedList<String>();
        linkedList.add("hello");
        linkedList.add("list");
        linkedList.add("java");

        linkedList.addFirst("this is"); linkedList.removeLast(); System.out.println(linkedList); }}Copy the code

Effect:

 

The Set collection

java.util

Interface Set<E>

Using the Set collection requires the package util

  • public interface Set<E>
    extends Collection<E>
    Copy the code

The Set inherits from the Collection and all its functionality comes from the Collection

  • A collection that does not contain repeating elements. More formally, the collection does not contain a pair of elements E1 and e2, such that e1.equals(e2), and at most one empty element. As its name implies, this interface simulates mathematical set abstraction.

    The Set interface adds additional provisions in addition to the contracts inherited from all constructors of the Collection interface and from the add, Equals, and hashCode methods. Declarations of other inheritance methods are also included here for convenience. (The specifications that accompany these declarations have tailored the Set interface, but they do not contain any additional provisions.)

    The extra stipulation for constructors is not surprising; all constructors must create a collection (as defined above) that does not contain repeating elements.

    Note: If mutable objects are used as setting elements, you must be very careful. If the value of an object changes in a way that affects the equals comparison, and the object is a member of the collection, the behavior of the collection is not specified. A special case of this prohibition is when a collection is not allowed to have itself as an element.

Set features

  • A collection that does not contain repeating elements
  • There are no indexed methods, so you can’t iterate with a normal for loop

 

Example:

public static void main(String[] args) {
        // Create a collection object
        Set<String> set = new HashSet<String>();

        set.add("and");
        set.add("no");
        set.add("or");

        //HashSet makes no guarantee about the iteration order of the collection
        for(String i:set){ System.out.println(i); }}Copy the code

Results:

 

Hash value

Hash: a value of type int calculated by the JDK based on the Object’s address or string or number

The hashCode() method: returns the hash value of an object

Example:

public static void main(String[] args) {
        Student s = new Student("Tong valley".25);
        System.out.println(s.hashCode());
}
Copy the code

Note: The hash values of the same object are the same

Overview of the HashSet collection

HashSet collection features

  • The underlying data structure is a hash table
  • There is no guarantee about the iteration order of the collection, that is, there is no guarantee that the elements stored and retrieved are in the same order
  • There are no indexed methods, so you can’t iterate with a normal for loop
  • Because it is a Set, it is a Set that contains no repeating elements

 

Hash table

  • Before JDK8, the bottom layer uses array + linked list implementation, can be said to be an array of elements for the linked list
  • After JDK8, when the length is relatively long, the underlying implementation of optimization

 

 

 

 

 

 

 

 

Learn together and make progress together. If there are any mistakes, please comment