Preface:

This is the 18th day of my participation in the August Genwen Challenge.More challenges in August

Java class set framework more, is also very important, here gives the diagram, can be understood as the corresponding inheritance relationship, can also be regarded as an important knowledge point review;

Collection interface

Inherited from: Iterable

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

Java.util. Collection is the largest parent interface for single-valued Collection operations, which has several core operations and common operations.

Modifier and Type Method(public) Description
boolean add(E e) Ensure that this collection contains the specified element (optional operation).
boolean addAll(Collection<? extends E> c) Adds all elements from the specified collection to this collection (optional operation).
void clear() Removes all elements from the collection (optional operation).
boolean contains(Object o) Returns true if the collection contains the specified element.
boolean remove(Object o) If present, a single instance of the specified element is removed from this collection (optional operation).
int size() Returns the number of elements in this collection.
Object[] toArray() Returns an array containing all elements of this collection.
Iterator<E> iterator() Returns an iterator that iterates over elements in this collection.

Two special methods are cotaines and remove. Both require the equals method to delete and query data; Otherwise, you can’t find the element.

And then there’s all the subclass methods that are derived.

The List collection

Main features: allows to save duplicate elements, and extends other methods on its parent interface;

Inheritance relationship:

public interface List<E> extends Collection<E>
Copy the code
Modifier and Type Method (public) Description
void add(int index, E element) Inserts the specified element at the specified position in this list (optional operation).
boolean add(E e) Appends the specified element to the end of this list (optional operation).
ListIterator<E> listIterator() Returns a list iterator over the elements in this list (in proper sequence).
static <E> List<E> of() Returns an unmodifiable list containing zero elements.
default void forEach(Consumer<? super T> action) Performs the given action for each element of the 可迭代 until all elements have been processed or the action throws an exception.

Example:

packageJava from entry to project practice. Java class set framework. Set the List;import java.util.List;
public classMultiple data preservation{
    public static void main(String[] args) {
        List<String> all = List.of("xbhg"."Hello"."World"."welcome");
        Object[] result = all.toArray();
        for (Object t: result) {
            System.out.println(t);
        }
        System.out.println("---------- splitter ----------");
        all.forEach(System.out::println); // The reference constructor for the method reference section}}Copy the code

ArrayList subclass

The inheritance structure is as follows:

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

Instantiation: Repeating elements are allowed to be saved in the order they were added;

packageJava from entry to project practice. Java class set framework. Set the List;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListinstantiationList {
    public static void main(String[] args) {
        List<String> all = new ArrayList<String>();
        all.add("Hello");
        all.add("Hello");
        all.add("Hello");
        all.add("xbhog");
        System.out.println(all);
        all.forEach(System.out::print);
        / / lambda expressions
        all.forEach((str)->{
            System.out.print(str+"、"); }); }}Copy the code

Set operation method:

packageJava from entry to project practice. Java class set framework. Set the List;import java.util.ArrayList;
import java.util.List;

public class ArrayLIstSet dependent operation{
    public static void main(String[] args) {
        List<String> all = new ArrayList<String>();
        System.out.println("Is the set empty?"+all.isEmpty()+Number of set elements+all.size());
        all.add("1");
        all.add("2");
        all.add("3");
        System.out.println("Is the set empty?"+all.isEmpty()+Number of set elements+all.size());
        System.out.println(all.get(1));
        System.out.println(all.remove("3"));
        System.out.println("Is the set empty?"+all.isEmpty()+Number of set elements+all.size()); }}Copy the code

ArrayList principle analysis: key

The first step is to make it clear that an ArrayList is implemented as an array; This raises the question of how ArrayList expands, and under what circumstances?

The arrays in the ArrayList class are created in space in the constructor; The corresponding parameterless and parameterless construction methods are as follows:

The no-argument constructor: initializes with an empty array (length 0) and allocates space for it the first time it is used (initialization degree 10);

public ArrayList(a) {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
Copy the code
// The default size of the open space
private static final int DEFAULT_CAPACITY = 10;
/** * Shared empty array instance used for empty instances. */
private static final Object[] EMPTY_ELEMENTDATA = {};
/** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
Copy the code

Parameter constructor: if the length is greater than 0, the specified length opens up the array space; If the length is 0, the method of no-parameter construction is adopted. If it is negative, an ILLegaLArgumentException is thrown;

public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if((size = elementData.length) ! =0) {
        // defend against c.toArray (incorrectly) not returning Object[]
        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
        if(elementData.getClass() ! = Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA; }}Copy the code

When the array is expanded, the data in the old array is copied to the new array.

Its maximum extent is:

/** * The maximum size of array to allocate (unless necessary). * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
Copy the code

ArrayList holds custom class objects:

This operation must include the related add, delete, change, check; Because the implementation of contains and remove methods need to be done by object comparison; So we need to override equals

packageJava from entry to project practice. Java class set framework. Set the List;import java.util.ArrayList;
import java.util.List;

class Person{
    private String name;
    private int age;
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }

    public String getName(a) {
        return name;
    }

    public int getAge(a) {
        return age;
    }

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

    public void setAge(int age) {
        this.age = age;
    }
    public boolean equals(Object obj){
        if(this== obj) return true;
        if(obj == null) return false;
        if(! (objinstanceof Person)) return false;
        Person pe = (Person) obj;
        return this.name.equals(pe.name) && this.age == pe.age;
    }

    @Override
    public String toString(a) {
        return "Name:"+this.name +", Age:+this.age; }}public class ArrayListSave custom class objects{
    public static void main(String[] args) {
        List<Person> std = new ArrayList<Person>();
        std.add(new Person("xbhog".1));
        std.add(new Person("Xiao Ming".2));
        std.add(new Person("White".3));
        System.out.println("------- Data content before deletion ----------");
        std.forEach((person)->{
            System.out.println("Name:"+person.getName()+", Age:+person.getAge());
        });
        System.out.println("------- Deleted data content ----------");
        std.remove(new Person("White".3));
        std.forEach((person)->{
            System.out.println("Name:"+person.getName()+", Age:+person.getAge());
        });
        System.out.println("------- Check whether the data exists ----------");
        System.out.println(std.contains(new Person("Xiao Ming".2))); }}Copy the code

LinkedList subclass:

The inheritance structure is as follows: implementation based on linked list form

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable
Copy the code

Implement the collection operation for LinkedList:

packageJava from entry to project practice. Java class set framework. Set the List;import java.util.LinkedList;
import java.util.List;

public class LinkListList operation{
    public static void main(String[] args) {
        List<String> all = new LinkedList<String>();
        all.add("java");
        all.add("python");
        all.add("Linux");
        System.out.println(all);
        System.out.println(all.get(2));
        System.out.println(all.get(1)); }}Copy the code

The Vector subclass:

The inheritance structure is as follows:

public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Copy the code

From its inheritance structure, Vector subclasses are used in the same way ArrayList is used;

packageJava from entry to project practice. Java class set framework. Set the List;import java.util.List;
import java.util.Vector;
public class VectorThe subclass implementationListinterface{
    public static void main(String[] args) {
        List<String> all = new Vector<String>();
        all.add("asda");
        all.add("Hello");
        all.add("buhao"); System.out.println(all); }}Copy the code

Difference:

Here is the vector operation, which is synchronized; Thread-safe, but not as efficient as ArrayList;

We should only use vector subclasses if we consider concurrent thread access.

public synchronized void copyInto(Object[] anArray)
Copy the code

The end:

If you see here or just to help you, hope to point a concern or recommendation, thank you;

There are mistakes, welcome to point out in the comments, the author will see the modification.