Java arrays, look at this one is enough

Before Java generics, only arrays can be used to specify the type of object storage; in autoboxing That is, before the emergence of the generic and automatic packing mechanism; mechanism occurs before, only arrays can be used to store basic data types , an array of components in Java among important.

Moreover, the array is also a most efficient storage and random access sequence objects way, but unfortunately, the length of the array is fixed - for example, it was created when the specified length is 6, you can store six elements when you want to put the first seven elements, it can not be done.

With the upgrading of computer hardware capabilities, developers to store a set of data when more willing to use ArrayList instead of an array. Although the internal ArrayList is achieved through an array, but compared with the array, its capacity can grow automatically, there are a lot of features not found arrays. You can not use the array do not use arrays unless the use arrays to improve performance issues.

01, create an array

Let's give a clear definition under Java arrays - arrays used to store fixed length of the same type of element.

Examples are as follows:

int[] ints = new int[3];
ints[0] = 1;
ints[1] = 2;
ints[2] = 3;

int ints1[] = new int[3];

int[] ints2 = { 1, 2, 3 };
复制代码

int[] intsCompared to int ints1[]a preferred declaratively, int ints1[]style comes from C / C ++ language, ease of C / C ++ programmers can quickly understand the Java language.

There are ways to create an array of two ways, one is by newkeyword, specifying the length, then by array[index] = valueway of assignment; another way is by {value1, value2, ...}way of direct assignment to create and at the same time.

The most common application is as follows (the date string placeholders):

private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd",
			"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM" };
复制代码

02, careful length

When using List and Map can directly size()obtain the actual container size (length) method. Array also have a key lengthto get the size (length), but the meaning is different. lengthShows only the size of the array to accommodate the actual size of the element, rather than the array.

For example as follows:

int[] ints = new int[3];
ints[0] = 1;
ints[1] = 2;

System.out.println(ints.length); // 输出3
复制代码

Although the actual length is 2 ints, but ints.lengththe length of it is 3-- beware.

03, Arrays tools

Java designers can be described as good intentions, specially designed an exclusive array of tools - , java.util.Arraysthere are several common methods to introduce us.

1)sort()

sort()The method used to sort the array, this method requires the elements of the array to achieve Comparable interface. If the element is not the sort of String or basic data types, you need to take the initiative to implement the Comparable interface (basic data types and String itself has been achieved Comparable interface).

Examples are as follows:

String[] strs = {"沉", "默","王", "二"};

Arrays.sort(strs);
System.out.println(Arrays.toString(strs));
// 输出[二, 沉, 王, 默]
复制代码

sort()The result of the sort method is [Second, Shen, Wang, Mo].

2)binarySearch()

binarySearch()The method used to carry out an array of binary search (return index value is located, is not found, then return -1), the method must first call before ordering.

Examples are as follows:

String[] strs = {"沉", "默","王", "二"};

Arrays.sort(strs);
System.out.println(Arrays.binarySearch(strs, "二"));
// 排序后的结果为[二, 沉, 王, 默]
// 二分查找的结果范围0
复制代码

Since the sort()result of sorting is a method [di, SHEN, Wang, Mo], it Arrays.binarySearch(strs, "二")returns the index value 0.

3)asList()

asList()A method for transforming into the array List (ArrayList), the following source code:

public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}
复制代码

How to convert it into an array List it? List by the toArray()method. May be experienced by an array of different ways to bring defined with reference to the embodiment of nuances.

String[] strs = {"沉", "默","王", "二"};

List<String> list = Arrays.asList(strs);
System.out.println(list);
// 输出[沉, 默, 王, 二]

String[] strs1 = new String[list.size()];
System.out.println(Arrays.toString(list.toArray(strs1)));
// 输出 [沉, 默, 王, 二]

String[] strs2 = new String[5];
System.out.println(Arrays.toString(list.toArray(strs2)));
// 输出 [沉, 默, 王, 二, null]

String[] strs3 = new String[1];
System.out.println(Arrays.toString(list.toArray(strs3)));
// 输出 [沉, 默, 王, 二]

String[] strs4 = {};
System.out.println(Arrays.toString(list.toArray(strs4)));
// 输出 [沉, 默, 王, 二]
复制代码

When the array size declared exceeds the size of the List, toArray()the array after the method will be converted to fill the seats ( null).

4)toString()

toString()Method for the array output string format ( [value1, value2, value3, ...]format), the following source code:

public static String toString(Object[] 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(String.valueOf(a[i]));
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}
复制代码

Previous: the Java String, look at this is enough

Next: the Java collection classes Beginners

Micro-channel search " silence the king, " public number, reply 'attention after the free video "get 500G high-quality instructional videos ( already categorized ).

Guess you like

Origin juejin.im/post/5dc52714518825139c52d59f