Java beginners learn something (10)

Posted by DJ Judas on Fri, 24 Dec 2021 12:40:25 +0100

1.ArrayList

You can use the official API to query:

There is a sub interface under Collection called List

There is an implementation class under the List interface called ArrayList

The bottom layer of ArrayList is array

ArrayList is also a container for storing data

Source code analysis

/**
     * Default initial capacity.
     The default variable, whose value is 10 # the default initialization capacity
     */
    private static final int DEFAULT_CAPACITY = 10;
/**
     * Shared empty array instance used for empty instances.
     Declared an empty array EMPTY_ELEMENTDATA variable
     */
    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.
     Empty array of default capacity
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
 /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     The valid capacity size of the array is 0 by default
     */
    private int size;
 /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     Constructor, which calls the constructor with parameters when instantiating
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
 /**
     * Constructs an empty list with an initial capacity of ten.
     Parameterless construction method
     An empty array with initialization capacity of 10 is constructed
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
​
​//Expansion method. When the capacity of the array is insufficient, it will be automatically expanded
 private void grow(int minCapacity) {
        // overflow-conscious code
     //oldCapacity is the old capacity
        int oldCapacity = elementData.length;//Only 10 elements can be placed in 10 capacity arrays
     //newCapacity new capacity (oldcapacity > > 1); Called bit operator
     //  int newCapacity = oldCapacity + oldCapacity * 0.5;
     //int newCapacity = 1.5 * oldCapacity;// The capacity expansion is 1.5 times that of the original array
     //The original data is 10. The capacity after expansion is 15
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
     //After capacity expansion, assign values to the array
     //[1,2,3,4,5,6,7,8,9,10] original array
     //[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] when assigning an array, the capacity of the array is 15
     //The capacity of the array is expanded. There are data in the new array and the old array
        //So use the copy method
        elementData = Arrays.copyOf(elementData, newCapacity);
    }


Often encounter interview questions:
Characteristics of ArrayList processing data:
Adding and deleting data is slow. Why?
Low data efficiency:
               1. It may involve the expansion of the array and the copy of the array
               2. When adding data to the specified location, it will cause the overall backward movement from the location where the data is added
Inefficient data deletion:
Starting from deleting data, the whole data moves forward one bit
Find fast. Why?
Search with index
It's like a book with a catalogue. If you want to find a chapter with page number, turn to page number directly
The number of pages is the index
The cpu directly locates the elements in the collection by accessing the memory address (array + subscript)
       
ArrayList is generally used in development. There are too many queries in development, because there are more queries, and there will be relatively few additions and deletions.
       
       
For the time complexity, the search is 1 and the addition and deletion is n

2.LinkedList

The parent interface is List

It and ArrayList are brothers. However, ArrrayList is used in development instead of LinkedList

Two way linked list: Bicycle Chain

LinkedList is a queue

Queue: first in first out (for example, people who line up first do nucleic acid first, and those who line up later do nucleic acid later)

Stack: first in and then out (for example, when a group of people squeeze into the elevator to the first floor, the people who squeeze in first are the innermost, and the people who squeeze in later are the outermost. When the elevator stops, the people who squeeze in later come out first, and the people who squeeze in first come out later)

Interviews often ask

Characteristics and differences between ArrayList and LinkedList

ArrayList and LinkedList are implementation classes of the List interface

ArrayList is fast in querying data, but it is slow in adding and deleting

LinkedList is slow to query and fast to add and delete

The underlying layer of linkedList is a two-way linked list structure

Slow search: it is because the binary search algorithm is used (binary search method is a method in data structure, you can learn about it)

[1,2,3,4,5,6,7,8,9,10] for example, find the number 3,

[1,2,3,4,5] [6,7,8,9,10] one score is 2

[1,2,3,4,5] is divided into 2

[1,2,3] [4,5]

[1,2,3] is further divided into 2

[1,2] [3] found 3

The query was performed n times and the LinkedList search was performed n times. It did not come out once

Fast addition and deletion: because the underlying LinkedList is a node internal class.

In development, we only use ArrayList instead of LinkedList. Because we use more website queries in the future. There are few additions and deletions, and the efficiency is hardly affected when using ArrayList

3.Object class

The Object class is the base class of all classes, including:

toString(); method

equals(); method

The equals method under the Object class compares the addresses of the two objects strictly

public boolean equals(Object obj) {
 return (this == obj);
}
==The memory address and content are compared, which is relatively strict

The equals under the String class compares the contents. This fully illustrates one point. The String class must override Object

The following equals method. xdm let's look at the source code:

public boolean equals(Object anObject) {
        //First, check whether the two addresses are the same. If the addresses of the two objects are the same, the contents must be the same
     if (this == anObject) {
         return true;
     }
     if (anObject instanceof String) {
         //Strong turn "have a cup of Java coffee" = value
         // "Have a cup of Java coffee" = otherstring value
         String anotherString = (String)anObject;
         int n = value.length;//Length of string 9
         if (n == anotherString.value.length) {
             //Why compare the length of two strings first?
             //When comparing two strings, if the length is different, the two strings must not be equal
             //If the two strings are equal in length, the contents of the string are compared immediately
             char v1[] = value;//[come on, one, J,a,v,a, coffee, coffee]
             char v2[] = anotherString.value;//[come on, one, J,a,v,a, coffee, coffee]
             int i = 0;
             while (n-- != 0) {
                 if (v1[i] != v2[i])
                     //If the two string character arrays are compared one by one through a loop. If one character is not equal, false is returned
                     return false;
                 i++;
             }
             //If the content is consistent, it is also true
             return true;
         }
     }
     return false;
 }

int hashCode(); method

The hashCode method obtains the hash value of the object, which is also called hash code. In fact, it is a decimal int type value

This value is the data from the object's memory address (hexadecimal) to hexadecimal

Official Manual:

If two objects are equal according to the equals(Object) method, calling the hashCode method on each of the two objects must produce the same integer result.

Common interview questions:

Why must the hashCode method be overridden when the equals method is overridden?

When two objects are compared using the equals method, if the objects are the same, the hash code may be different

The hash code must be the same during development.

If the hash code is the same, the object must be the same

4.Set set

Set parent interface is Collection

Set and List are brothers

The characteristics of List sets are: ordered and repeatable

Set features are: disordered and unrepeatable

There are two implementation classes under the Set interface:

HashSet TreeSet

There are no unique methods in the Set interface, just the methods under the Collection interface

Set is also less used in development

Topics: Java