This post is from my blog

The text before

The last article examined the source code for the constructors and basic operations of ArrayList. This time, I will cover the rest of the common methods of ArrayList (save the iterators for next time).

The main content

  1. Container capacity
  2. Basic uses for finding specific elements, including specific elements, cloning, etc

The body of the

Capacity refers to the capacity of the container, and size refers to the number of elements in the container

Let’s get straight to the point

Expansion and 1.

  • Set the capacity
Public void ensureCapacity(int minCapacity) {// Int minExpand = (elementData! = DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any sizeif not default element table
            // larger than default fordefault empty table. It is already // supposed to be at default size. //: DEFAULT_CAPACITY; // If the given is larger than the above, the given is usedif(minCapacity > minExpand) {// Use the following method ensureExplicitCapacity(minCapacity); Private void ensureExplicitCapacity(int minCapacity) {modCount++; // Increase capacity // overflow-conscious codeif (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
Copy the code
  • growth
/**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limitPrivate static final int MAX_ARRAY_SIZE = integer. MAX_VALUE - 8; private static final int MAX_ARRAY_SIZE = integer. MAX_VALUE - 8; /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; Int newCapacity = oldCapacity + (oldCapacity >> 1); // Use the larger one as the capacityif(newCapacity - minCapacity < 0) newCapacity = minCapacity; // The operation is performed when the capacity is extremely largeif(newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }Copy the code
  • The large capacity
Private static int hugeCapacity(int minCapacity) {// Overflowif (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
Copy the code


2. Adjust the size

If you find that there is a lot more capacity and it is a bit wasteful, you can resize the container to its current size

    public void trimToSize() { modCount++; // If you do have extra partsif(size < elementData.length) {// If size is not 0, copy array elementData = (size == 0)? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); }}Copy the code


3. Number of list elements

    public int size() {
        return size;
    }
Copy the code


4. Check whether the list is empty

    public boolean isEmpty() {
        return size == 0;
    }
Copy the code


5. Find the location of a specific element in the list

    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else{// Search through the number groupfor (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return- 1; }Copy the code


6. Determine if the list contains a specific element

    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
Copy the code


7. If there are multiple specific elements in the list

    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else{// start traversal from the tailfor (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return- 1; }Copy the code


Cloning of 8.

One concept needs to be explained first: shallow copy and deep copy

Shallow copy, two ArrayLists have different addresses in memory, but their elements point to the same address.

Not only is the memory address of the ArrayList different, but the elements in the ArrayList do not point to the same address.

Deep copy is a little bit easier to understand, where everything is copied, completely separate

ArrayList **clone()** is a shallow copy.

public class Test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        for(int i = 0; i < 10; i++) { list.add(String.valueOf(i)); } // Cast ArrayList<String> list1 = (ArrayList<String>)list.clone(); System.out.println("list" + list);
        System.out.println("list1" + list1);
        System.out.println("Are they the same for a particular element?" + (list.get(1) == list1.get(1)));
        System.out.println("Do they have the same address?"+ (list == list1)); }}Copy the code


9. Convert to an array

An ArrayList is a list. Unlike an array, you can’t access elements directly with subscripts. You can convert an array to an array in two ways:

// Copy the elements of the list into an array in the order of the elements in the list.toArray() {
        return Arrays.copyOf(elementData, size);
    }
Copy the code


This method may throw an array storage exception and a null pointer exception. Here are two cases where the array size is smaller than the number of list elements:

  1. The array type passed in is the same as the list element or the base type of the list element, and the list element is directly assigned to the array

  2. The array type passed in is not the base type of the list element, throwing an array storage exception

Public <T> T[] toArray(T[] a) {// The size of the array passed is smallerif(a.length < size) // Create an array of the runtime type of array Areturn (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
Copy the code

The array s passed in is of type Object, which conforms to case 1 above:

Here’s case two:

With that in mind, the usual methods for arrayLists are done, and the next article will be on the use of iterators related to ArrayLists