Java Array manipulation: Arrays Tool class

Source: Internet
Author: User
Tags comparable shallow copy

Java.util.Arrays provides a number of tool methods to manipulate arrays, all of which are static methods.

1 Easy to create List

public static <T> list<t> aslist (T ... a)

Returns a list of fixed sizes supported by the specified array.

 Public static <T> list<t> aslist (T ... a) {        returnnew arraylist<> (a);    }

Typical usage:list<string> stooges = arrays.aslist ("Larry", "Moe", "Curly");

22 points Find

There are multiple overloads of the method. Like what

public static int BinarySearch (long[] A,long key)
public static Intbinarysearch (object[] A, int fromIndex, int toindex, Object key)
public static <T> int BinarySearch (t[] a,int fromindex,int toindex,t key,comparator<? Super T> C)

A binary lookup requires an array to be ordered, and the elements in the array to be comparable in size.

3 Copying an array

There are multiple overloaded versions.

(1) public static <T> t[] CopyOf (t[] original, int newlength)
Copies the specified array, intercepts it, or fills it with null (if necessary) so that the copy has the specified length. This method copies the original array into a new array, where length is the size of the new array. If length is less than original array, the new array is the preceding length element of the original array, and if length is greater than the length of the original array, the new array is all elements of the original array, supplemented by 0,false or null.

(2) public static <T> t[] Copyofrange (t[] original, int. from, int. to)

Similar to the above method, this method only copies the from index of the original array to the elements of the to index.

System.arraycopy method

The Arraycopy method signature for the system class is as follows:

public static void Arraycopy (Object src,int srcpos,object dest,int destpos,int length)

The bottom of all methods of copying an array in the arrays class is to call the System.arraycopy method, which is a local static method. For a primitive type array, the method implements a deep copy, whereas for an array of objects, the System.arraycopy method is just a shallow copy. This means that the method simply copies the original array object itself, and does not copy the object that each data element in the array points to. That is, each array element in the new array still points to the same object as the individual elements in the original array. This creates a problem: Modifying the properties of an object pointed to by an array element in the new array, the object of the array element corresponding to the previous array is also modified.

See Example:

Importjava.util.Arrays;classStudent {Private Static intCount = 1000; Private intid = count++; PrivateString name = "No." +ID;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; } @Override PublicString toString () {return"Student [id=" + ID + ", name=" + name + "]"; }} Public classArraycopytest { Public Static voidMain (string[] args) {student[] old=NewStudent[] {NewStudent (),NewStudent (),NewStudent (),}; student[] Fresh=NewStudent[5]; System.arraycopy (old,0, fresh, 0, old.length); System.out.println ("Old:" +arrays.tostring (old)); System.out.println ("Fresh:" +arrays.tostring (fresh)); fresh[2].setname ("Obama"); fresh[2].setid (9999); System.out.println ("Old:" +arrays.tostring (old)); System.out.println ("Fresh:" +arrays.tostring (fresh)); }}
View Code

Output Result:

old:[student [id=1000, name=no.1000], Student [id=1001, name=no.1001], Student [id=1002, name=no.1002]]
fresh:[student [id=1000, name=no.1000], Student [id=1001, name=no.1001], Student [id=1002, name=no.1002], NULL, NULL]
old:[student [id=1000, name=no.1000], Student [id=1001, name=no.1001], Student [id=9999, Name=obama]]
fresh:[student [id=1000, name=no.1000], Student [id=1001, name=no.1001], Student [id=9999, Name=obama], NULL, NULL]

The program was intended to modify student information in the fresh[2] of the fresh array, resulting in the corresponding student information in the old array being modified.

First look at the memory diagram, which is the program execution Fresh[2].setname ("Obama"); Fresh[2].setid (9999); memory layout before two lines of code:

The following is the program execution Fresh[2].setname ("Obama"); Fresh[2].setid (9999); memory layout after two lines of code:

The reason is obviously, not much to say.

Additional information: Clone method in Object

The Clone method in object is similar to System.arraycopy, and clone is a protected method. if all data fields in an object are numeric or basic, there is no problem with such a copy. However, if a reference to a child object is included in the object, the result of the copy causes two domain references to point to the same child object, so the original object and the cloned object share this part of the information. that is, the default clone operation is a shallow copy, which does not clone the inner object contained in the object.

Because the Clone method is declared as protected, only the subclass can invoke the protected clone method to clone itself. Other objects cannot invoke the Clone method of an object.

Solution: Redefine the Clone method and declare it as public, and implement a markup interface, cloneable, that tells other objects to invoke the Clone method of the class.

For example, you can rewrite the following clone method for the student class above:

@Override      Public throws clonenotsupportedexception{        = (Student)Super. Clone ();         New // re-assigning a value to a data field that is not a primitive type        return cloned;    }
View Code

4 Printing array elements

public static String toString (object[] a)
Returns a string representation of the contents of the specified array. Like [element[0].tostring,element[1].tostring,...]

public static String deeptostring (object[] a)
This method is designed to convert a multidimensional array to a string.

52 Arrays are equal

public static Boolean Equals (Object[] a,object[] A2)
Returns true if the two specified Objects arrays are equal to each other. If two arrays contain the same number of elements, and all corresponding element pairs in the two arrays are equal, the two arrays are considered equal. if (E1==null e2==null:e1.equals (E2)), the two objects E1 and E2 are considered equal. In other words, if two arrays contain the same elements in the same order, the two arrays are equal. In addition, if two array references are NULL, they are considered equal.

public static Boolean Deepequals (object[] A1, object[] A2)
Returns true if two of the specified arrays are deeply equal to each other. This method applies to nested arrays of any depth.

6 hash value

public static int hashcode (object[] a)
Returns a hash code based on the contents of the specified array. This hash code consists of the hash code of the array element.

public static int Deephashcode (object[] a)
Returns a hash code based on the "deep content" of the specified array.

7 Assigning a value to an array

public static void Fill (object[] A, Object val)
Sets the value of all array elements of an array to Val.

8 sort

public static void sort (short[] a)
Sorts the specified array of objects in ascending order based on the natural ordering of the elements. All elements in an array must implement the comparable interface.

public static <T> void sort (t[] a,comparator<? super T> C)
Sorts the specified array of objects according to the order produced by the specified comparer.

Java Array manipulation: Arrays Tool class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.