Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Basic knowledge of

Many truths can often be put into simple words. There are only two things you need to remember about Java arrays:

1. An array is an ordered collection of data of the same type.

2. Arrays are also objects.

Expanded version:

  1. The length is fixed and unchangeable;
  2. The type cannot be changed;
  3. Types can be basically referrable;
  4. The variables of data are reference types, arrays are objects, and the elements of data are attributes of objects.

There are three ways to initialize Java arrays:

  1. Static initialization: the value is given at the beginning;
  2. Dynamic initialization: start with a length and then assign values one by one;
  3. Default initialization: initialize the previous step dynamically, and then use the default values given by the system: 0, 0.0, false, null.

Practice:

  1. Array.toString([]);
  2. System.arraycopy(The original array, the index from the original array, the array to be copied, the index from the target array, the length of the copy from the original array);
  3. for(type i: array)Let’s go through them one by one;
  4. Initialization method;

The exercise code is as follows:

public class CopyArray {
    public static void main(String[] args) {
        String[] companies = new String[]{"alibaba"."bytedance"."pinduoduo"."dingdong"."souhu"};
        String[] copy2 = new String[3];
        System.arraycopy(companies, 0, copy2, 0.3);

        for(String s: copy2) { System.out.println(s); }}}/** result: * Alibaba * bytedance * pinduoduo */
Copy the code
public class Test02 {

    public static void main(String[] args) {
        Static initializers are initialized directly after the declaration.
        Man m = new Man(20."SuperKris");
        // Man[] mans = new Man[6]; This line is almost useless
        Man[] mans = new Man[]{
                new Man(10."Kris0"),
                new Man(11."Kris1"),
                new Man(13."Kris3"),
                new Man(12."Kris2"),
                new Man(15."Kris5"),}; mans[4] = m;

        for (int i=0; i<mans.length; i++) {
            System.out.println(mans[i].getName());
        }
        // Enhance the for loop to take out each element and place it in the variable.
        for(Man man: mans) { System.out.println(man); }}}class Man {
    private int id;
    private String name;
    
    public Man(a) {}public Man(int id, String name) {
        this.id = id;
        this.name = name;
    }
  
    @Override
    public String toString(a) {
        return "id = " + id + ", name = " + name;
    }
    // omit JavaBean ()
   
}
Copy the code
public class Test03 {
    public static void main(String[] args) {
        int[] a = {100.200.300};
        int[] b = {1.2.3.4234.22.45.765};

        System.out.println(Arrays.toString(a));

        Arrays.sort(b);
        System.out.println(b.toString());
        // Binary search
        System.out.println("b: " + Arrays.toString(b));
        // Return the index if it exists
        System.out.println("The index of this element is:" + Arrays.binarySearch(b, 22));
        // If the number does not exist, return a negative number
        System.out.println("The index of this element is:" + Arrays.binarySearch(b, 555));

        // Copy b from fromIndex to toindex-1 as the last parameter [)
        Arrays.fill(b, 0.3.500); System.out.println(Arrays.toString(b)); }}Copy the code

The running result is shown as follows:

tip

Source code (hold Alt/ Command in IDEA and hover the mouse over the desired location to access it)

There are two caveats:

1. Array.tostring () is not the same as the toString in the previous String or Object.

This is the normal toString method:

public String toString(a) {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Copy the code

Static array.toString () {array.tostring () {array.tostring ();

public static String toString(int[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append('] ').toString();
        b.append(","); }}Copy the code

2. Why does the binary method return an index if a number cannot be found- 6?

At this time we can take a look at the source code to see the truth.

Binary search source:

private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                 int key) {
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high) {
        int mid = (low + high) >>> 1;
        int midVal = a[mid];

        if (midVal < key)
            low = mid + 1;
        else if (midVal > key)
            high = mid - 1;
        else
            return mid; // key found
    }
    return -(low + 1);  // key not found.
}
Copy the code

Then you’ll notice that in the last line: if not, the nearest left index +1 is taken by default, followed by a negative number.

And there is a very detailed place, dichotomy to take the middle of the word, the source with a displacement operation, no formula, effectively prevent overflow. (For more on dichotomy, read “How to Gracefully Implement Binary Lookup” at juejin.cn/post/701598…)

A very simple mistake I made:

Type error caused by wrapping other classes in a class;

System. Arraycopy without main method.