Interview beginner Java development and ask Arrays

  • 2021-11-01 03:16:12
  • OfStack

Catalog 1. Basic Definition 2. Summary of Common Methods

1. Basic definitions

Arrays class, full path java. util. Arrays, the main function is to operate arrays, all methods of Arrays class are static methods, so

Calling mode is all Arrays. Method name

2. Common methods


1. <T> List<T>  asList(T... a)

The array can be converted into the corresponding list collection, but it can only be converted into list. The asList method builds an internal static class ArrayList.

This ArrayList is also inherited from AbstractList, but it is not the ArrayList commonly used in our collection. There is a difference between the two,

The internal static class AbstractList also implements contains, forEach, replaceAll, sort, toArray and other methods, but add, remove and other methods do not


Integer[] array = new Integer[]{1,2,3}; int[] array2 = new int[]{1,2,3};
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(array);// Join Java Develop and exchange samples: 5931423281 Blowing water and chatting 
List<int[]> list3 = Arrays.asList(array2);

2. void fill(int[] a, int val)、void fill(int[] a, int fromIndex, int toIndex, int val)、void fill(Object[] a, Object val)、void fill(Object[] a, int fromIndex, int toIndex, Object val)

The fill method has multiple overloads corresponding to several basic data types and reference types (Object),

fill(int[] a, int val) Overwrites the entire array of values as val

fill(int[] a, int fromIndex, int toIndex, int val) Optional beginning and ending are provided (excluding)


int[] array = new int[]{1,2,3};
Arrays.fill(array, 1);
Arrays.fill(array, 0, 2, 1);// {1,1,3}
String[] str = {"123"};
Arrays.fill(str, "1");

The source code is as follows:

We can see that the overloaded method with optional beginning and end will check the array out of bounds first to prevent illegal input


   /** * Assigns the specified double value to each element of the specified
     * range of the specified array of doubles.  The range to be filled
     * extends from index <tt>fromIndex</tt>, inclusive, to index
     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
     * range to be filled is empty.)
     *
     * @param a the array to be filled
     * @param fromIndex the index of the first element (inclusive) to be
     *        filled with the specified value
     * @param toIndex the index of the last element (exclusive) to be
     *        filled with the specified value// Join Java Develop and exchange samples: 5931423281 Blowing water and chatting 
     * @param val the value to be stored in all elements of the array
     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
     *         <tt>toIndex &gt; a.length</tt> */
    public static void fill(double[] a, int fromIndex, int toIndex,double val){
        rangeCheck(a.length, fromIndex, toIndex); for (
        int i = fromIndex; i < toIndex; i++)
            a[i] = val;
    } /** * Assigns the specified float value to each element of the specified array
     * of floats.
     *
     * @param a the array to be filled
     * @param val the value to be stored in all elements of the array */
    public static void fill(float[] a, float val) {
     for (int i = 0, len = a.length; i < len; i++)
            a[i] = val;
    } /** * Checks that {@code fromIndex} and {@code toIndex} are in
     * the range and throws an exception if they aren't. */
    private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) { 
    if (fromIndex > toIndex) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
        } if (fromIndex < 0) { 
        throw new ArrayIndexOutOfBoundsException(fromIndex);
        } if (toIndex > arrayLength) {// Join Java Develop and exchange samples: 5931423281 Blowing water and chatting 
         throw new ArrayIndexOutOfBoundsException(toIndex);
        }
    }

3. int[] copyOf(int[] original, int newLength)、int[] copyOfRange(int[] original, int from, int to)

There are multiple overloading modes, and here int is an example

From the sample i, we can see that the array length after copyOf copying can be larger than the array before copying. According to the source code, the excess elements are filled with 0, and the reference type is filled with null


int[] array = new int[]{1,2,3}; 
int[] array2 = Arrays.copyOf(array, 4);

public static int[] copyOf(
int[] original, int newLength) { 
int[] copy = new int[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
                          return copy;
    }

For copyOfRange, you can choose the beginning and end of the copy (excluding), and the end subscript can be longer than the length of the original array, and the excess subscript will be filled


int[] array = new int[]{1,2,3,4,5,6,7,8,9}; 
int[] array2 = Arrays.copyOfRange(array, 3, 6); 
int[] array3 = Arrays.copyOfRange(array, 3, 10);

   /** * Copies the specified range of the specified array into a new array.
     * The initial index of the range (<tt>from</tt>) must lie between zero
     * and <tt>original.length</tt>, inclusive.  The value at
     * <tt>original[from]</tt> is placed into the initial element of the copy
     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
     * Values from subsequent elements in the original array are placed into
     * subsequent elements in the copy.  The final index of the range
     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
     * may be greater than <tt>original.length</tt>, in which case
     * <tt>0</tt> is placed in all elements of the copy whose index is
     * greater than or equal to <tt>original.length - from</tt>.  The length
     * of the returned array will be <tt>to - from</tt>.
     *
     * @param original the array from which a range is to be copied
     * @param from the initial index of the range to be copied, inclusive
     * @param to the final index of the range to be copied, exclusive.
     *     (This index may lie outside the array.)
     * @return a new array containing the specified range from the original array,
     *     truncated or padded with zeros to obtain the required length
     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
     *     or {@code from > original.length}
     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
     * @throws NullPointerException if <tt>original</tt> is null
     * @since 1.6 */// Join Java Develop and exchange samples: 5931423281 Blowing water and chatting 
    public static int[] copyOfRange(int[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); int[] copy = new int[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength)); return copy;
    }

4. boolean equals(int[] a, int[] a2)、boolean equals(Object[] a, Object[] a2)

If two arrays are equal, the elements of the basic type will be judged by == in turn, and the reference type will use equals "Bai Piao Data" after being judged empty


public static boolean equals(int[] a, int[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true;
    } public static boolean equals(Object[] a, Object[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) {
            Object o1 = a[i];
            Object o2 = a2[i]; if (!(o1==null ? o2==null : o1.equals(o2))) return false;
        } return true;
    }

5. String toString(int[] a)

Suppose we want to output all the elements of an array. One way is to loop through all the elements and output them one by one

However, Arrays provides a scheme that can be called directly, and the internal implementation of toString is actually realized through traversal.

Using the variable string StringBuilder


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(", ");
        }
    }

6. int binarySearch(int[] a, int key)

Arrays built-in 2-point search method, using the condition that the parameter array a is ordered, such as unordered

Causes an error in the return result


Integer[] array = new Integer[]{1,2,3}; int[] array2 = new int[]{1,2,3};
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(array);// Join Java Develop and exchange samples: 5931423281 Blowing water and chatting 
List<int[]> list3 = Arrays.asList(array2);
0

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: