[Java Basics] Study Notes 5 - Introduction to packaging classes and collections

fourth stage

Packaging

Packing and unpacking as well as manual and automatic

package chapter4;

public class Pack {
    
    
    public static void main(String[] args) {
    
    
        // 自动装箱
        int a = 100;
        Integer aa = a;
        // 自动拆箱
        int b = aa;

        // 手动装箱
        Integer a2 = Integer.valueOf(a);
        // 手动拆箱
        int b2 = a2.intValue();
    }
}

String

Several features of the string class

  1. Implemented the interface Serializable (supports serialization), and Comparable (indicates that it can be compared)
  2. It is a final class and cannot be inherited
  3. He has an attribute value, which is used to store string content
  4. value is modified by final and cannot be modified directly

Direct assignment String s1 = "asd": Check from the constant pool to see if there is space for asd, and if so, point directly to it; if not, reset it and point to it;
s1 eventually points to the address of the constant pool.

Constructor assignment String s2 = new String("asd"): Create space in the heap first, maintain the value attribute, and point to the asd space; if the constant pool does not have asd, re-create it and point it through value;
s2 finally points to the address in the heap


str = s1 + s2Variable addition operates in the constant pool;

str = "asd" + "asd"Constant addition, the operation is in the heap;


StringBuffer

Both StringBuffer and StringBuilder are variable character sequences. They are not directly terminated by final like String.

StringBuffer is thread-safe, but StringBuilder is not

When the string buffer is used by a single thread, it is recommended to use StringBuilder directly because it is better optimized and faster.


Since the value attribute of String is final, every time we add a string type variable, we actually throw away the old copy first, generate a new result and reassign it to the variable; this will cause a large number of copies to remain in the memory. Fragmentation, affecting performance


Arrays

Use Arrays to perform basic operations on arrays

package chapter4;

import java.util.Arrays;

public class ArraysDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    1, 2, 3};
        System.out.println(Arrays.toString(arr));
        Arrays.sort(arr);
        System.out.println(Arrays.binarySearch(arr, 3));
    }
}

Pass in the custom comparable interface to diversify the sorting methods
and implement descending sorting.

package chapter4;

import java.util.Arrays;
import java.util.Comparator;

public class ArraysDemo {
    
    
    public static void main(String[] args) {
    
    
        Integer[] numbers = {
    
    5, 2, 8, 1, 9};

        // 使用自定义的Comparator进行降序排序
        Arrays.sort(numbers, new Comparator<Integer>() {
    
    
            @Override
            public int compare(Integer a, Integer b) {
    
    
                // 降序排序,将比较结果反转
                return b.compareTo(a);
            }
        });

        // 输出排序结果
        for (Integer number : numbers) {
    
    
            System.out.println(number);
        }
    }
}

System

System.arraycopyExecute array copy.
The five parameters are: original array, original array starting index, target array, target array starting index, and how many elements to copy.

package chapter4;

import java.util.Arrays;

public class SystemDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] arr1 = {
    
    1, 31, 4, 12, 3, 12};
        int[] arr2 = new int[3];
        System.arraycopy(arr1, 0, arr2, 0, 3);
        System.out.println(Arrays.toString(arr2));
    }
}

BigInteger is a large integer type.
You need to use the methods provided by the large number type to perform addition, subtraction, multiplication and division operations.

In the same way, there is also a high-precision decimal and large number operation

package chapter4;

import java.math.BigInteger;

public class BigNum {
    
    
    public static void main(String[] args) {
    
    
        BigInteger bigInteger1 = new BigInteger("12839371293");
        BigInteger bigInteger2 = bigInteger1.add(bigInteger1);
        System.out.println(bigInteger2);
    }
}

Collection

Collection is an interface in Java for storing and manipulating a set of objects.

The Collection interface defines some commonly used methods, as follows:

  • boolean add(E element): Adds an element to the collection.
  • boolean remove(Object element): Removes an element from the collection.
  • boolean contains(Object element): Checks whether the collection contains the specified element.
  • int size(): Returns the number of elements in the collection.
  • boolean isEmpty(): Checks if the collection is empty.
  • void clear(): Clear all elements in the collection.
  • Iterator<E> iterator(): Returns an iterator for traversing the elements in the collection.
  • boolean addAll(Collection<? extends E> collection): Adds all elements from another collection to the current collection.
  • boolean removeAll(Collection<?> collection): Removes elements from the current collection that are identical to another collection.

Common Collection subinterfaces include:

  • List: An ordered collection that allows duplicate elements.
  • Set: A collection that does not allow duplicate elements.
  • Queue: Queue interface, which defines methods for inserting and deleting operations in a collection.
  • Map: A collection of key-value pairs, each element contains a key and a value.

Can be traversed with the help of iterator

package chapter5;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IterateDemo {
    
    
    public static void main(String[] args) {
    
    
        List<String> list = new ArrayList<>();
        list.add("shit");
        list.add("fuck");

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){
    
    
            String str = (String) iterator.next();
            System.out.println(str);
        }

    }
}

ArrayList

The underlying implementation is an array, which is not recommended under multi-thread conditions.

ArrayList internally uses an array of Object type to store elements.

When you create an ArrayList, an array with an initial capacity of 10 is created by default. As elements are added, if the capacity of the array is insufficient to store the new elements, ArrayList will automatically expand, usually by half of the current capacity.

ArrayList can directly access and modify elements through index (time complexity is O(1)). Insertion and deletion operations involve moving elements (O(n) on average).

Frequent insertion and deletion operations in ArrayList may cause the array to be reallocated and copied, resulting in performance degradation.


ArrayList maintains an elementData array by default
. If constructed without parameters, its capacity is 0; the initial initialization capacity becomes 10, and each subsequent capacity increase is 1.5 times;
if the capacity is specified during initialization, subsequent expansions will increase by 1.5 times each time;


Source code analysis

  1. Class declaration and member variables: The ArrayList class is declared as public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable. It implements the List interface and inherits the AbstractList class. Among them, Eis a generic parameter, indicating the type of elements stored in ArrayList. ArrayList also implements other interfaces, such as RandomAccess (supports fast random access) and Cloneable (supports cloning).

  2. Member variables: There are two important member variables inside ArrayList:

    • private static final int DEFAULT_CAPACITY = 10: The default initial capacity is 10.
    • private static final Object[] EMPTY_ELEMENTDATA = {}: When the ArrayList is created without specifying an initial capacity, use this empty array as initial storage.
  3. Construction method:

    • public ArrayList(): No-argument constructor, creates an empty ArrayList with default initial capacity.
    • public ArrayList(int initialCapacity): Constructor that specifies the initial capacity and creates an empty ArrayList with the specified initial capacity.
    • public ArrayList(Collection<? extends E> c): A constructor that receives a collection parameter and creates an ArrayList containing collection elements.
  4. Core methods:

    • public boolean add(E element): Add elements to the end of the ArrayList.
    • public void add(int index, E element): Insert an element at the specified position.
    • public E get(int index): Get the element at the specified position.
    • public E remove(int index): Delete the element at the specified position and return the deleted element.
    • public boolean remove(Object element): Delete the first matched element.
    • public int size(): Returns the number of elements in the ArrayList.
  5. Expansion mechanism:

    • When an element is inserted, if the current capacity is insufficient, the capacity will be expanded. When expanding, create a new array with a larger capacity and copy the elements in the original array to the new array.
    • The expansion strategy is to expand by half of the current capacity, that is, the new capacity is 1.5 times the original capacity.
    • The expansion operation ensureCapacityInternalis implemented through methods.

Vector

Vector is a dynamic array implementation in the Java collection framework. Vector is similar to ArrayList, but it is thread-safe and therefore more suitable for use in multi-threaded environments.

  1. Class declaration and inheritance: The Vector class is declared as public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable. It implements the List interface and inherits the AbstractList class. Similar to ArrayList, Eit is a generic parameter indicating the type of elements stored in Vector. Vector also implements other interfaces, such as RandomAccess (supports fast random access) and Cloneable (supports cloning).

  2. Thread safety: Vector is thread-safe. Vector achieves thread safety by using keywords on key methods synchronized, ensuring atomic operations on shared data.

  3. Construction method:

    • public Vector(): No-argument constructor, creates an empty Vector with an initial capacity of 10.
    • public Vector(int initialCapacity): Constructor that specifies the initial capacity and creates an empty Vector specifying the initial capacity.
    • public Vector(int initialCapacity, int capacityIncrement): Specify the construction method of initial capacity and capacity increment, and create an empty Vector of initial capacity and capacity increment.
    • public Vector(Collection<? extends E> c): A constructor that receives a collection parameter and creates a Vector containing collection elements.
  4. Core methods:

    • public synchronized boolean add(E element): Add elements to the end of Vector.
    • public synchronized void add(int index, E element): Insert an element at the specified position.
    • public synchronized E get(int index): Get the element at the specified position.
    • public synchronized E remove(int index): Delete the element at the specified position and return the deleted element.
    • public synchronized boolean remove(Object element): Delete the first matched element.
    • public synchronized int size(): Returns the number of elements in Vector.

In a single-threaded environment, if thread safety is not required, it is recommended to use ArrayList instead of Vector because ArrayList has better performance.


Guess you like

Origin blog.csdn.net/delete_you/article/details/132698156