Array Introduction
Arrays and other containers have three advantages: Efficiency, Type Recognition And Can hold primitives .
Arrays are among the many methods in Java that can store and access the reference sequence at random, the most efficient one. .
An array is a simple linear sequence that allows you to quickly access its elements.
However, the speed is costly. When you create an array, its capacity is fixed and cannot be changed in its lifecycle.
Maybe you will propose to create an array first, and then create a new one when it is not enough,
Import all the references in the old array to the new one.
In fact, this is what arraylist will do later. However, the overhead brought by this flexibility makes arraylist much less efficient than array.
Java performs a boundary check on both arrays and containers. If the boundary is exceeded, it returns a runtimeexception (indexoutofboundsexception ).
Generic container classes include list, set, and map. They process objects as if they do not have their own specific types.
That is to say, the container regards all the elements contained in the object as (the root class of all classes in Java) (the generic type is introduced in Java and should still be processed as an object ).
In this way, you only need to create a container to put all types of objects into it. From this point of view, this approach is very good (only suffering from primitive.
If it is a constant, you can also use Java's primitive Wrapper class; if it is a variable, it can only be placed in your own class ).
Compared with other generic containers The second advantage of array: when creating an array, you also specify the type of the object it holds.
(This introduces the third point -- The array can hold primitives. , But containers do not work. ).
That is to say, it will perform a type check during compilation to prevent you from inserting objects of the wrong type, or you may mistakenly type the objects during object extraction.
Java can prevent you from passing an inappropriate message to an object during compilation and running. This does not mean that using containers is dangerous,
However, if the compiler can help you specify the program, the program runs faster and the end user will receive less harassment due to program running exceptions.
From the perspective of efficiency and type check, array is always correct.
Note: The generic type is introduced in Java. Although the generic container class still treats elements as objects,
However, generic containers can recognize types, so the array type recognition has no advantage.
Arrays are essentially objects.
No matter what type of Array you use, the array identifier is actually a reference for "creating real objects in heap.
In fact, the object holds the reference of other objects. You can use the array initialization Statement (see example 1) to implicitly create this object,
You can also use the new expression (see example 2) to explicitly create this object. The read-only Length attribute tells you how many elements an array can store.
It is a part of an array object (actually the only property or method you can access ). The '[]' syntax is another way to access array objects.
You cannot know how many elements are put in the array, because length only tells you how many elements can be put in the array, that is, the size of the array object,
Instead of the number of actually held elements. However, when an array object is created, its reference is automatically initialized to null,
Therefore, you can check whether a "slot" of the array is null to determine whether it holds the object.
Similarly, the primitive array automatically initializes the number to zero, the character is initialized to (char) 0, and the Boolean value is initialized to false.
Example 1: Use the array initialization statement to implicitly create this object.
Int IDs [] = {0, 2, 3 ,};
Example 2: Use the new expression to create the array object
Int IDs [] = new int [3];
Primitive container
The container class can only hold the reference of the object. In addition to Objects Reference, Arrays can also directly hold primitive.
Of course, wrapper classes such as integer and double can be used. Put the primitive value in the container, which is a little strange.
In addition, primitive arrays are much more efficient than wrapper containers. Of course, if you use primitive,
You also need the flexibility of the container class that can be automatically expanded as needed, so you cannot use arrays. You can only use containers to store primitive Wrapper Classes.
Returns an array.
Suppose you write a method, and it returns not one but a group of things. In Java, "an array" can be returned ".
Unlike C ++, you never have to worry about the Java array-As long as you still need it, it will remain; once you have used up, the garbage collector will help you clean it.
Arrays class
Java. util contains an arrays class, which includes a set of static methods that can be used for arrays. These methods are some practical tools.
There are four basic Methods: To compare the equals () of two arrays; To fill the fill (); to sort the array sort ();
And binarysearch () used to search for elements in a sorted array ().
All these methods overload primitive and object. In addition, there is an aslist () method that accepts an array and converts it into a list container.
Note: Fill () is to fill a value in the entire array (such as fill (INT [] array, int value ))
Or an array (such as fill (INT [] array, int start, int end, int value )).
Therefore, fill () is powerless if you want to add the numbers that are generated immediately to the array.
Copy an array
The Java Standard Library provides a static method of system. arraycopy. Compared with the for loop, it can copy arrays at a faster speed (it should be copied using memory ).
System. arraycopy () is overloaded for all types. Both the object array and the primitive array can be copied.
However, if you copy an object array, you only copy their reference-the object itself will not be copied. This is used as a shallow copy ).
Array comparison
To compare whether the array is completely equal, arrays provides the overloaded equals () method. Of course, it is also for a variety of primitive and object.
To make the two arrays completely equal, they must have the same number of elements, and each element of the array must be equal to the element at the corresponding position of the other array. .
Use equals () to determine the equality of elements. (For primitive, it uses equals () of its Wrapper class; for example, int uses integer. Equals (). Is that true? Is this necessary? ).
Note 1 : Primitive comparison. I think the values of long, Int, short, byte and char should be directly compared.
For floating point numbers: I think double is called compare (double double1, double double2), float is compared by calling compare (float float1, float float2.
Why do floating point numbers not be compared directly with values. I think it is meaningless to leave the fractional part of a floating point far away from the decimal point.
Note 2 : Although arrays compares float arrays, the descriptions are the values are compared in the same manner as float. Equals ().
The comparison of the double array is also described as the values are compared in the same manner as double. Equals ().
However, float. Equals ()/double. Equals () is used for comparison.
I think arrays calls compare (double double1, double double2) for the floating point number: double, and float calls compare (float float1, float float2) for comparison.
Double. Equals () calls compare (double double1, double double2), and float. Equals () calls ompare (float float1, float float2 ).
Therefore, their comparison results are the same. As the document says, they are in the same way.
Array Element comparison
Arrays has three types of array comparison:
First, comparison of Basic Types :
INTEGER (long, Int, short, byte) and character (char): directly compare values.
Float/double; call the compare method in the container class.
Second: comparison through the comparable Interface .
This method requires that the object in the array must implement the comparable interface. Otherwise, a classcastexception is thrown.
Arrays provides the following functions:
Public static void sort (object [] array)
Public static void sort (object [] array, int start, int end)
To implement the java. Lang. Comparable interface, you must implement the compareto (t another) method.
This method can take another object as a parameter. If the existing object is smaller than the parameter, it returns a negative number,
If they are the same, zero is returned. If the existing object is greater than the parameter, a positive number is returned.
Third: Use a personalized comparator (which implements the comparator interface ).
Assume that someone has given you a class that does not implement the comparable interface, or this class implements the comparable interface,
However, you find that it does not work as expected, so you need to redefine a new comparison method.
Java does not require you to insert the comparison code into the class. Its solution is to use "strategy design pattern )".
With a policy, you can encapsulate the changed code (that is, the code for comparison) into its own class (that is, the so-called strategy object ).
You give the policy object to the code that does not change, and then use it to complete the entire algorithm. In this way, you can use different policy objects to represent different comparison methods,
Then they are all handed over to the same sorting program.
The policy object is the object that implements the comparator interface. .
The comparator interface has two methods: Compare (T object1, t object2) and equals (Object object ).
The compare () method returns a negative integer, zero, or positive integer based on whether the first parameter is smaller than, equal to, or greater than the second parameter.
However, unless there are special performance requirements, you do not need to implement equals (). As long as it is a class, it implicitly inherits from the object,
The object already has an equals. Therefore, you can use the equals () of the default object to meet the interface requirements.
In the collections class, there is a comparator that will return the opposite of the object's proprietary comparative method. It can be easily used on comptype.
Collections. reverseorder ()/reverseorder (comparator <t> C) returns a comparator reference.
Sorting of Arrays
With the built-in sorting method, you can sort any array, whether primitive or object array,
As long as it implements the comparable interface or has a related comparator object.
The sorting algorithm used by the java standard library has been optimized.
For primitive, it uses "Quick Sort". For objects, it uses "stable merge sort )".
So unless prolier indicates that the sorting algorithm is a bottleneck, you don't have to worry about performance.
Query ordered arrays
Once the array is sorted, you can use arrays. binarysearch () for quick query.
However Avoid Binarysearch () is used for an unsorted array, because the result is meaningless.
If arrays. binarysearch () is found, it returns a value greater than or equal to 0. Otherwise, it returns a negative value,
The negative value indicates which value should be inserted if you manually maintain the array.
The value is-(insert point)-1.
The "insert point" refers to the subscript of the smallest value among all values that are greater than the value to be searched,
Or, if all values in the array are smaller than the value to be found, it is a. Size ().
If the array contains repeated elements, it cannot guarantee which one will be returned. This algorithm does not support repeated elements, but it does not report an error.
Therefore, if you need an ordered sequence with no repeated elements,
You can use the treeset ("sorted order" supported) and hashset ("sorted order" supported) described later in this chapter "]).
These two classes will help you look after all the details. Only when you encounter performance bottlenecks should you replace these two classes with manually maintained arrays.
If comparator is used for sorting (for object arrays, comparator is not allowed for primitive arrays,
You must also use the same comparator (the reload version using this method ).
Summary of the array Section
All in all, if you want to hold a group of objects, the first choice and the most efficient choice should be array.
In addition, if this is a set of primitive, you can only use arrays. There are some more general situations,
That is, when writing a program, you do not know how many objects to use, or use a more complex method to store objects.
Therefore, Java provides the container class )". Its basic types include list, set, and map.
They also have some other features. For example, if all the objects held by set are different, map is a "associative array )",
It can establish a connection between two objects. In addition, unlike arrays, they can be automatically adjusted, so you can place any number of objects in them.