Arrayutils source Reading:) (COMMONS-LANG3)

Source: Internet
Author: User

These two days just waiting to allocate the process of thinking to create their own code base, but then think about the world so big, I think of the east of the things you are basically free of charge, for the HA do not connect the hands, applause, thanks!

All right, let's start with a arrayutils about it:
As the name implies, this goods is used for array operation OH. However, this tool class is a lot of about 6000 lines of said, provide the function is relatively more complete. There are probably the following major classes of methods (in fact, they are generally overloading):

    • Empty_ ... Array
      This type of attribute is not used directly and is generally used as the return value in the following methods
    • Tostring
      When working with arrays, we often need to look at the exact values of the array, especially when debugging, it is often troublesome to perform the appropriate viewing operation.
      The following code uses the JDK's own tool method, which is also a good choice, but in arrayutils for null values you can specify an alternative value.
System.out.println(Arrays.deepToString(array))
  • Hashcode
    Generates an array of hashcode, especially for multidimensional arrays OH
  • Tomap
    This should be considered as a simple way to create a map, mainly to convert the two-dimensional array to map, of course, the second dimension needs to have two-bit elements, respectively, as the map of the key and value
  • ToArray
    We can use this method when we have an indefinite number of homogeneous elements, which we put into the array, and then return, very generous.
  • Clone
    For the copy of the array, it is best to use this method, first arrayutils to do a full overloading, and then its implementation is to call the array type itself method Clone (), to know that the underlying implementation is native way, That speed is conceivable.
    Of course, it is more obvious that since Arrayutils itself is called the array of built-in methods why do we have to superfluous it? It is true that there is not a big gap here, but what if the array to be cloned is NULL? So, Arrayutils still for us to save something, not to say that good programmers are lazy children:
  • Nulltoempty
    Think of the first attribute? It works, as long as the array is null or array.length () = = 0 Then you will get this Empty array, except that it is a set of elements that cannot be changed, and can be used as a flag
  • Subarray
    Again, this method is not difficult for us to implement ourselves, but it makes a lot of judgments and finally improves the efficiency of element replication by invoking the native method.
  • Issamelength
    Similarly, the thin comparison process can handle the case of an array of NULL
  • GetLength
    Get length by native way
  • Reverse
    Overloading a number of methods for reversing arrays, and also supports reversing some of the child elements in an array
  • IndexOf
    The implementation of this method is actually beyond my guess. Is it a magical way to think about it before you look at it? The use of a relatively simple approach, one-to-the-other. However, in its overloading, there is a one-time query for multiple identical data optimization scheme, this will be combined with the final method to explain.
  • LastIndexOf
    Similar to the previous, only the order was adjusted.
  • Contains
    This implementation of the way is also a bit out of my expectation, the original call indexOf to judge.
  • Toprimitive
    The array elements are all converted to the base type, when there is null in the array must specify the value of the substitution, otherwise the method without the substitution value of the call will be error, after all, null and any basic type have no corresponding value, so be sure to pay attention.
  • Toobject
    Contrary to the function of the above method
  • IsEmpty
    Simplified array-judging method
  • AddAll
    The absolute combination of two arrays Oh, the null array can be done, just give it, it will help you to combine them
  • CopyArrayGrow1
    Have you ever felt that the name of this method is tall, so clear that I almost don't believe in my eyes? To tell you the truth, I never used the Arabic numerals in the method name. As the name implies, copy and then increase the space of 1. Of course, the real implementation is to create a new array of length + 1, and then use the native method to copy.
  • Add
    Well, forget to say, the above method is private, others are for this method of service, there is wood is very convenient, the first impression of the array should be the length of the immutability it:) But people arrayutils do not eat you this set, help us to achieve the addition of the array. Magic, but the method called is the top of the CopyArrayGrow1, is not very frank.
  • Remove
    As with add, remove can also make the array length 1 less, which is exactly the reverse of the
  • Removeelement
    The difference between this and the previous method is that the previous deletion is based on the index of the element, and the next one is to find the specified array element before deleting it.
  • RemoveAll
    This method is still very interesting, there will be posted source code for the total reward
  • Removeelements
    This method is similar to the above, except that the parameter is already the corresponding array subscript

Highlighting RemoveAll, it is also a overloading player:

StaticObject RemoveAll (FinalObject Array,Final int... indices) {Final intLength = getlength (array);intdiff =0;//number of elements that need to be removed        if(Isnotempty (indices)) {Arrays.sort (indices);//Sorting is critical for removal, from small to large            inti = indices.length;//Total number of removed            intPrevindex = length;//calculated from the end of the array             while(-I. >=0) {//This removes the validation of the element's legitimacy, as well as removing the subscript beyond the array range, repeating the subscript                Final int Index= Indices[i];if(Index<0||Index>= length) {Throw NewIndexoutofboundsexception ("Index:"+Index+", Length:"+ length); }if(Index>= Previndex) {Continue; } diff++;//1 increase as long as you meet the situationPrevindex =Index; }        }FinalObject result = Array.newinstance (Array.getclass (). Getcomponenttype (), Length-diff);//Indicates the length of the new array that was eventually formed        if(diff < length) {//If the number to be removed equals the length of the array itself, it must be an empty array.            intend = length;//The remaining length of the current original array            intDest = Length-diff;//The target array length is not currently populated             for(inti = indices.length-1; I >=0; i--) {Final int Index= Indices[i];//point to the element I need to remove                if(End-Index>1) {//equivalent to (CP > 0), end is only length                    Final intCP = End-Index-1; Dest-= CP;//target array The starting subscript of the receiving elementSystem.arraycopy (Array,Index+1, result, dest, CP);//Afer This copy, we still has a for dest items.} end =Index; }if(End >0) {//You need to execute this block as long as the removed subscript is not 0 o'clockSystem.arraycopy (Array,0, result,0, end); }        }returnResult }

Another type of removeall is similar to the previous one, with the subsidy code, and the method used to invoke it (overloading) uses a more interesting algorithm, which is affixed to the total reward:

  Public Static Boolean[] Removeelements (Final Boolean[] Array,Final Boolean... values) {if(IsEmpty (array) | | IsEmpty (VALUES)) {returnClone (array);//clone Original Array}FinalHashmap<boolean, mutableint> occurrences =NewHashmap<boolean, Mutableint> (2);The //Boolean type is only two, true, false:)         for(Final BooleanV:values) {//Here is the preprocessing of this algorithm, very important OH            FinalBoolean boxed = boolean.valueof (v);FinalMutableintCount= Occurrences.get (boxed);if(Count==NULL) {Occurrences.put (boxed,NewMutableint (1)); }Else{Count. increment ();//Final statistics out false, true number removed separately}        }FinalBitSet Toremove =NewBitSet ();//Here is a more interesting thing to do        //We can come up with a topic that gives an array and a set of numbers that need to be queried in the array, to find the corresponding subscripts, and to allow duplicate objects to exist        //The most common practice is that the number to be looked up is exhaustive, compared with the elements in the array, which is basically the complexity of O (NM).        //But this algorithm on the high-end point, limited capacity, it is not clear how this complexity to write-_-| |, the Great god know of also hope pointing guidance, grateful AH:)        //But it's essentially the same as the normal method, but it reduces the time it takes for a repeating element to be exhaustive .         for(FinalMap.entry<boolean, mutableint> E:occurrences.entryset ()) {FinalBoolean v = e.getkey ();intFound =0;//Based on the number of repetitions to find the corresponding number of times             for(inti =0, CT = E.getvalue (). Intvalue (); i < CT; i++) {found = IndexOf (array, V.booleanvalue (), found);if(Found <0) { Break;            } toremove.set (found++); }        }return(Boolean[]) RemoveAll (array, toremove); }

Please also point out the error, Sierra:)

Arrayutils source Reading:) (COMMONS-LANG3)

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.