The previous section focuses on the basic concepts of arrays, a little bit more about what an array is, and the other aspects of the array in this blog post.
Third, performance? Please consider the array first
There are many ways to store a series of data in Java, and it is more convenient to operate than arrays. But why do we need to use arrays instead of replacing them? There are three aspects to the difference between an array and other kinds of containers: efficiency, type, and the ability to preserve basic types. In Java, an array is the most efficient way to store and randomly access an object's reference sequence.
Arrays are used more and more in project design, and it is really not easy to use lists and sets, but there are some advantages to arrays in some ways, such as speed, and the bottom of the collection class is also implemented by arrays.
--------This is ArrayList's add ()------Public Boolean Add (E e) { ensurecapacity (size + 1); Increments modcount!! elementdata[size++] = e; return true; }
Here are some operational comparisons using arrays and lists.
First, sum
Long time1 = System.currenttimemillis (); for (int i = 0; i < 100000000; i++) { sum + = arrays[i%10]; } Long time2 = System.currenttimemillis (); System.out.println ("The sum of the array takes time:" + (TIME2-TIME1) + "milliseconds"); Long Time3 = System.currenttimemillis (); for (int i = 0; i < 100000000; i++) { sum + = List.get (i%10); } Long time4 = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("List sum takes time:" + (Time4-time3) + "milliseconds"),--------------Output: Array summation takes time: 696 milliseconds the list sum takes time: 3498 milliseconds
From the above time consumption, the velocity of the sum of the array for the base type is about 5 times times that of the set. In fact, in the list collection, there is a fatal action in the summation: List.get (i). This action is a unboxing action, the integer object is automatically converted to an int base type by the Intvalue method, where unnecessary performance consumption is generated.
Therefore, consider the array in the scenario where performance requirements are high.
Four, variable-length arrays?
Arrays are fixed-length, and cannot be changed once the declaration is initialized. This is very inconvenient for us in the actual development, intelligent we certainly can find a way to achieve. Just as Java cannot implement multiple inheritance, we can use internal classes and interfaces as well (see: Java Boost (ix)-----implement multiple inheritance).
So how do you implement variable-length arrays? We can use the Add method inside the list collection to simulate the implementation of the concept of expansion. Here is the method of ArrayList expansion:
public void ensurecapacity (int mincapacity) { modcount++; int oldcapacity = elementdata.length; /** * If the length of the current need exceeds the length of the array for expansion processing * /if (Mincapacity > Oldcapacity) { Object olddata[] = elementdata; int newcapacity = (oldcapacity * 3)/2 + 1; Expansion if (Newcapacity < mincapacity) newcapacity = mincapacity; Copy an array, generate a new array elementdata = arrays.copyof (Elementdata, newcapacity);} }
What this piece of code does for us is behind the IF statement. The idea is to copy the original array into a new array, which is 1.5 times times the length of the original array. So the analog array expansion code is as follows:
public class Arrayutils {/** * @desc expansion of arrays * @author Chenssy * @data 2013-12-8 * @param <T> * @param datas Original array * @param newlen expansion size * @return t[] * * public static <T> t[] Expandcapacity (t[] Datas,int newlen) {Newlen = Newlen < 0? datas.length:d atas.length + newlen; Generates a new array of return arrays.copyof (Datas, Newlen); }/** * @desc an array for expansion processing, 1.5 times times * @author Chenssy * @data 2013-12-8 * @param <T> * @param da Tas original array * @return t[] * * public static <T> t[] Expandcapacity (t[] datas) {int Newlen = (datas.le Ngth * 3)/2; Expands 1.5 times times the original array//generates a new array of return arrays.copyof (Datas, Newlen); /** * @desc the array for expansion processing, * @author Chenssy * @data 2013-12-8 * @param <T> * @param datas Original array * @param mulitiple of expansion * @return t[] * * public static <T> t[] Expandcapacitymul (t[] Datas,int Mulitiple) { mulitiple = mulitiple < 0? 1:mulitiple; int Newlen = Datas.length * mulitiple; Return arrays.copyof (Datas,newlen); }}
In this roundabout way, we can realize the expansion of the array. So if you really need a variable-length dataset in the project, and the array is within the scope, we can't repel him because he's a fixed length!
V. Array replication issues
I used to make a copy of the collection because the collection does not have a copy of the method, so one of the replication is very troublesome, so I simply use List.toarray () method to convert the array and then through the arrays.copyof copy, in the conversion into a set, personally feel very convenient, but I have fallen into the trap! We know that if an array element is an object, the data inside the array is the object reference
public class Test {public static void main (string[] args) {person person_01 = new Person ("chenssy_01"); person[] persons1 = new person[]{person_01}; person[] Persons2 = arrays.copyof (persons1,persons1.length); System.out.println ("Array persons1:"); Display (PERSONS1); System.out.println ("---------------------"); System.out.println ("Array persons2:"); Display (PERSONS2); Change its value persons2[0].setname ("chessy_02"); System.out.println ("------------------------after changing its value"); System.out.println ("Array persons1:"); Display (PERSONS1); System.out.println ("---------------------"); System.out.println ("Array persons2:"); Display (PERSONS2); } public static void display (person[] persons) {for (person person:persons) {System.out.println (pers On.tostring ()); }}}-------------Output: Array persons1: Name is: chenssy_01---------------------array persons2: Name is: chenssy_01------------After changing its value------------array persons1: Name is: chessy_02---------------------array persons2: Name is: chessy_02
The results show that the values in the persons1 have also changed, which is a typical shallow copy problem. So the array produced by the arrays.copyof () method is a shallow copy. The Clone () method of the array is also the Clone () method of the collection, so we must pay attention to the shallow copy when using the Copy method.
For a copy of the depth of the blog, refer to:
Gradual analysis of shallow and deep copies of Java: Http://www.cnblogs.com/chenssy/p/3308489.html. To implement a copy of an object using serialization: Http://www.cnblogs.com/chenssy/p/3382979.html. Six, array conversion to List note place
We often need to use the Aslist () method of the arrays tool to convert it to a list. Convenience is convenient, but sometimes there are puzzling problems. As follows:
public static void Main (string[] args) { int[] datas = new int[]{1,2,3,4,5}; List List = Arrays.aslist (datas); System.out.println (List.size ()); } ------------output:1
The result is 1, yes you did not read wrong, the result is 1. But why would it be 1 instead of 5? First look at the source of Aslist ()
public static <T> list<t> aslist (T ... a) { return new arraylist<t> (a); }
Note This parameter: T...A, this parameter is a generic variable length parameter, we know that the basic data type is not possible to generics, it is said that 8 basic data types are not available as generic parameters, but why the compiler did not error? This is because in Java, the array is treated as an object, it can be generic, so our program is to use an array of type int as the type of T, so after the conversion there will be only one element of type int array. So our program System.out.println (datas.equals (list.get (0))), and the output is definitely true. Of course, if you change int to integer, the length becomes 5.
We are looking at the following procedure:
Enum Week{sum,mon,tue,web,thu,fri,sat} public static void Main (string[] args) { week[] weeks = {Week.sum, WEEK.MON,WEEK.TUE,WEEK.WEB,WEEK.THU,WEEK.FRI}; list<week> list = arrays.aslist (weeks); List.add (Week.sat); }
This program is very simple, that is to say an array into a list, and then change the value in the collection, but run it?
Exception in thread "main" java.lang.UnsupportedOperationException at Java.util.AbstractList.add ( abstractlist.java:131) at Java.util.AbstractList.add (abstractlist.java:91) at Com.array.Test.main ( TEST.JAVA:18)
Compile yes, but the operation unexpectedly has an abnormal error! Unsupportedoperationexception, the exception is thrown when the requested operation is not supported. In a way, the Add method is not supported, and we know it is impossible! What causes this anomaly? First look at the source code for Aslist ():
public static <T> list<t> aslist (T ... a) { return new arraylist<t> (a); }
Here is the return of a ArrayList object directly, but note that this ArrayList is not java.util.ArrayList, but rather an inside of the Arrays tool class:
private static class Arraylist<e> extends Abstractlist<e> implements Randomaccess, java.io.serializable{ private static final long serialversionuid = -2764017481108945198l; Private final e[] A; ArrayList (e[] array) { if (array==null) throw new NullPointerException (); A = array; } /** ellipsis method **/ }
But this inner class does not provide the Add () method, so look at the parent class:
Public boolean Add (E e) { Add (size (), e); return true; } public void Add (int index, E element) { throw new unsupportedoperationexception (); }
Here the parent class just provides the method, the concrete implementation of the method is not, so the concrete implementation needs the subclass to provide itself, but very sorry
This inner class ArrayList does not improve the implementation of the Add method. In ArrayList, it mainly provides the following methods:
1. Size: Number of elements
2, ToArray: converted to an array, the realization of a shallow copy of the arrays.
3, get: Gets the specified element.
4, contains: whether to include an element.
So in summary, Aslist returns a list of immutable lengths. How long the array is, and how long the list is converted to, we cannot add or remove to increase or decrease its length.
References: "Writing high-quality code-151 recommendations for improving Java programs"
Java Improvement Chapter (19)-----Array Two