Introduction to the use of Java arrays _java

Source: Internet
Author: User
Tags garbage collection numeric value shallow copy

There are three main differences between Java arrays and container classes: efficiency, type, and the ability to save basic types . In Java, an array is the most efficient way to store and randomly access an object reference sequence. An array is a simple linear sequence, which makes the element access very fast. But the price to pay for this is that the size of the array is fixed and cannot be changed in its lifecycle.

Because of the appearance of the paradigm and automatic packaging mechanism, containers can be used almost as easily as arrays for basic types. Arrays and containers can prevent you from abusing them to some extent, and if you cross the line, you get runtimeexception anomalies. The only remaining advantage of arrays is efficiency, however, if you want to solve more generalized problems, the array may be too restrictive, so most of the cases will choose the container.

Therefore, if you use the most recent Java version, you should prioritize the container instead of the array. You should refactor the program as an array only if you have proven that performance has become a problem and that you can improve performance by switching to arrays.

"Initialize"
Java array initialization is very restrictive, which effectively prevents misuse of arrays. If you initialize the error, you will get compileexception directly instead of runtimeexception. You cannot use this array reference to do anything until the arrays are properly initialized.
Arrays are defined with int[] array and int array[], generally using the first style, which separates the type from the variable name.
There are two ways to initialize an array, static initialization and dynamic initialization. The length must be specified when initializing, and the length of the first dimension of the multidimensional array must be indicated, and must be defined by the high dimensional to the low dimension. The initialization action can be anywhere in the code, and the {} method can only appear where the array is created. The specific initialization method See program:

Copy Code code as follows:



public class javaarrayinit{


public static void Main (String args[]) {


Int[] Arraya; Not initialized


int[] Arrayb = new INT[5]; Static initialization


System.out.println (arraya.length); Compileexception


System.out.println ("Arrayb Length:" + arrayb.length); Unable to get the actual number of elements saved





Arraya = new INT[10]; Dynamic initialization


System.out.println ("Arraya length:" + arraya.length);





int[] arrayc = new int[]{1,2,3,4};


System.out.println ("Arrayc Length:" + arrayc.length);





int[] Arrayd = new Int[1]{1}; Incorrect initialization, cannot define a peacekeeping initialization value at the same time





int[][] Arraye = new int[1][];


System.out.println ("Arraye Length:" + arraye.length);





int[][] Arrayf = new int[][2]; The length of the high dimension should be specified first





int[][] Arrayg = new int[][]{{1,2,3,4},{5,6,7},{7,24,23,24};


System.out.println ("Arrayg Length:" + arrayg.length);





int[][][] Arrayh = new int[][][]{{{1,2,3},{4,5,6},{7,8,9},{10,11,12}};


System.out.println ("Arrayh Length:" + arrayh.length);





Dummyarray[] Arrayi = {new Dummyarray (), New Dummyarray ()}; Custom array type


System.out.println ("Arrayi Length:" + arrayi.length);


System.out.println ("arrayi[1]:" + arrayi[1].getvalue ());





dummyarray[] Arrayk = new DUMMYARRAY[5];


System.out.println ("arrayk[0]:" + arrayk[0]); Null


for (int i = 0; i < arrayk.length; i++) {


Arrayk[i] = new Dummyarray ();


}


System.out.println ("arrayk[0]:" + arrayk[0].getvalue ()); 2


}


}


Class dummyarray{


private static int temp;


Private final int arrayvalue = temp++;


public int GetValue () {


return arrayvalue;


}


}

Output:

Arrayb Length:5
Arraya length:10
ARRAYC Length:4
Arraye length:1
ARRAYG Length:3
Arrayh length:1
Arrayi Length:2
ARRAYI[1]: 1
ARRAYK[0]: null
Arrayk[0]: 2




"Length"


Read-only member length is part of an array object (although the variable is not actually declared in the API and is dynamically generated at runtime), it is the only field or method that can be accessed. The [] syntax is the only way to access an array object, and the container is accessed through the Get () method. You can use Array.Length to get the size of the array, and note that you distinguish it from the string type String.Length (). Array uses the way member variables are used, and string uses the method of member methods. At the same time, Array.Length can only get the size of the array, not how many elements the array actually has. The length of a multidimensional array computes only the lengths of the first dimension.


Copy Code code as follows:



public class javaarraylength{


public static void Main (String args[]) {


int[] Arraya = new INT[15];


ARRAYA[1] = 1;


ARRAYA[2] = 2;


ARRAYA[3] = 3;


System.out.println ("Arraya length:" + arraya.length);





int[][] Arrayb = new int[10][];


System.out.println ("Arrayb Length:" + arrayb.length);





int[][] Arrayc = new int[][]{{1,1,1,2,},{1,1,2,3,4,5},{4,5,6,7,7},};//Note the comma following


System.out.println ("Arrayc Length:" + arrayc.length);





int[][] Arrayd = new int[][]{{1,1,1,2,},{1,1,2,3,4,5},{4,5,6,7,7},{};


System.out.println ("Arrayd Length:" + arrayd.length);


}


}


Output:

Arraya length:15
Arrayb length:10
ARRAYC Length:3
Arrayd Length:4




"Arrays.fill"


Arrays.fill is a very limited method because it can only fill each position with the same value (if it is an object, the same reference is copied). Using Arrays.fill, you can populate an entire array or an area of an array, but because Arrays.fill can only be invoked with a single numeric value, it is not very useful.





"Assignment and Reference"


Java array initialization has only a reference to an array, and does not allocate storage space to the arrays. Therefore, replication between arrays cannot be simply assigned with "=" because the same object is being manipulated. The following procedure:


Copy Code code as follows:



public class javaarrayquote{


public static void Main (String args[]) {


String testa = "Testa";


String testb = "Testb";


string[] Arraya = new string[]{"Arraya"};


string[] Arrayb = new string[]{"Arrayb"};


Testb = Testa;


TESTB = "Testb change";


System.out.println ("I ' m testa,i have no changed:" + testa);


Arrayb = Arraya;


Arrayb[0] = "Arrayb have changed";


System.out.println ("I ' M arraya, I have no changed:" + arraya[0]);





}


}


Output:

I ' m testa,i have no Changed:testa
I ' M arraya, I have no changed:arrayb have changed




As you can see, we change the value of arrayb[0] to change the array of references, so we output ARRAYA[0], actually, and arrayb[0.





"Array Replication"


Methods for copying arrays in Java:





1. Using a For loop to copy all or specified elements is less efficient


2. Use the Clone method to get the value of the array, not the reference. However, clones cannot replicate the specified elements, with less flexibility


3. Using the System.arraycopy (SRC, Srcpos, dest, Destpos, Length) method, the Java Standard Class library provides a static method, System.arraycopy (), which is much faster than a for-loop for copying arrays. System.arraycopy () is overloaded for all types, the base type array and the object array can be replicated with system.arraycopy (), but the object array simply copies the reference, and no copies of the two objects appear. This is called a shallow copy (shallowcopy).


SRC: source array;


Srcpos: The starting position to copy the source array;


Dest: Destination array;


Destpos: The starting position of the destination array placement;


Length: The size of the copy.


Note: system.arraycopy () will not be automatically wrapped and automatically disassembled, so two arrays must be of the same type or can be converted to the same type of array. At the same time, this method can also be used to copy the array itself.


int[] Test ={0,1,2,3,4,5,6};


System.arraycopy (test,0,test,3,3);


The result is: {0,1,2,0,1,2,6};


The test procedure is as follows:


Copy Code code as follows:



public class javaarraycopy{


public static void Main (String args[]) {


Int[] array = {1,2,3,4,5,6,7,8,9};


For Loop method


int[] Arraya = new INT[9];


for (int i = 0; i < arraya.length; i++) {


Arraya[i] = Array[i];


System.out.print (Arraya[i] + ",");


}


Test


System.out.println ("");


ARRAYA[1] = 19;


for (int i = 0; i < arraya.length; i++) {


System.out.print (Arraya[i] + ",");


}


System.out.println ("");


for (int i = 0; i < Array.Length; i++) {


System.out.print (Array[i] + ",");


}


System.out.println ("");





Clone method


int[] Arrayb = new INT[9];


Arrayb = Array.clone ();


Test


ARRAYB[1] = 19;


for (int i = 0; i < arrayb.length; i++) {


System.out.print (Arrayb[i] + ",");


}


System.out.println ("");


for (int i = 0; i < Array.Length; i++) {


System.out.print (Array[i] + ",");


}


System.out.println ("");





System.arraycopy method


int[] Arrayc = new INT[9];


System.arraycopy (array, 0, ARRAYC, 0, arrayc.length);


Test


ARRAYC[1] = 19;


for (int i = 0; i < arrayc.length; i++) {


System.out.print (Arrayc[i] + ",");


}


System.out.println ("");


for (int i = 0; i < Array.Length; i++) {


System.out.print (Array[i] + ",");


}


}


}





"Array Comparisons"


Arrays provides the overloaded equals () method, which is overloaded for all types and object types to compare the entire array. An array is equal if the number of elements must be equal, and the elements of the corresponding position are equal. Multidimensional arrays are compared using the Deepequals () method. The two arrays that are compared by the Array.equals () method must be arrays of the same type.


Copy Code code as follows:



Import Java.util.Arrays;


public class javaarrayequals{


public static void Main (String args[]) {


Int[] Arraya = {1,2,3};


Int[] Arrayb = {1,2,3,};


int[] Arrayc = new Int[4]; If int[] Arrayc = new Int[3],return True


Arrayc[0] = 1;


ARRAYC[1] = 2;


ARRAYC[2] = 3;


System.out.println (Arrays.equals (Arraya, Arrayb));


System.out.println (Arrays.equals (Arraya, ARRAYC));





String[][] Arrayd = {{"A", "B"},{"C", "D"}};


String[][] Arraye = {{"A", "B"},{"C", "D"}};


System.out.println (Arrays.deepequals (Arrayd, Arraye));


}


}





"Array Sorting and Lookup"


Arrays provide a built-in sort method, sort () that can be sorted on any base type array or array of objects (the object must implement the comparable interface or have an associated comparator). Java provides different sorting methods for different types----a quick sort for basic type design, and a "stable merge sort" for object design, so there is no need to worry about the efficiency of array sorting.


BinarySearch () is used to quickly find elements in a sorted array, and if you use BinarySearch () with an unordered array, you will have unpredictable results.





"Return Array"


C and C + + cannot return an array, only the pointer to an array is returned, because returning an array makes it difficult to control the life cycle of the array and can easily cause a memory leak. Java allows direct return of an array and can be reclaimed by the garbage collection mechanism.





"Array and container conversion" "Cannot convert base type array"





The array is converted to list:


Copy Code code as follows:



Import java.util.*;


public class arraytolist{


public static void Main (String args[]) {


String[] Arraya = {"A", "B", "C"};


List lista = java.util.Arrays.asList (Arraya);


System.out.println ("lista:" + lista);





Int[] Arrayb = {1,2,3};


List Listb = java.util.Arrays.asList (Arrayb);


System.out.println ("Listb:" + Listb);





Integer[] Arrayc = {1,2,3};


List LISTC = java.util.Arrays.asList (ARRAYC);


System.out.println ("LISTC:" + LISTC);


}


}


Output:


Lista: [A, B, c]
LISTB: [[i@de6ced]
LISTC: [1, 2, 3]




Why is int and integer output different?





List to array


Copy Code code as follows:



Import java.util.*;


public class listtoarray{


public static void Main (String args[]) {


list<string> list = new arraylist<string> ();


String[] Array;


List.add ("Testa");


List.add ("Testb");


List.add ("TESTC");


System.out.println ("list:" + list);





String[] strings = new string[list.size ()];


Array = List.toarray (strings);


for (int i = 0, j = array.length I < J; i++) {


System.out.print (Array[i] + ",");


}


}


}


The output is:

List: [Testa, Testb, TESTC]
Testa,testb,testc




"Remove Duplicate data"


Array and container conversions make it easy to remove array duplication, but if the array is too large, efficiency is a problem.


Copy Code code as follows:



Import java.util.*;


public class javaarrayunique{


public static void Main (String args[]) {


String[] Array = {"A", "B", "A", "a", "C", "B"};


Arrayunique (array);


Test


for (int i = 0, j = Arrayunique (array). length; i < J; i++) {


System.out.print (Arrayunique (array) [i] + ",");


}


}





public static string[] Arrayunique (string[] array) {


list<string> list = new arraylist<string> ();


for (int i = 0, j = array.length I < J; i++) {


if (!list.contains (Array[i])) {


List.add (Array[i]);


}


}


String[] strings = new string[list.size ()];


string[] Arrayunique = List.toarray (strings);


return arrayunique;


}


}





On the question of efficiency, I made a comparison that the array running 100,000 of data on my computer is about 577ms, while the data running 1 million data is about 5663MS. This is also related to the ability of the computer to run, but it is obviously incremented with the size of the array.


Copy Code code as follows:



Import java.util.*;


public class javaarrayunique{


public static void Main (String args[]) {


double[] array = new double[100000];


for (int i = 0, j = array.length I < J; i++) {


Array[i] = Math.ceil (Math.random () *1000);


}





double[] Arrayb = new double[1000000];


for (int i = 0, j = arrayb.length I < J; i++) {


Arrayb[i] = Math.ceil (Math.random () *1000);


}





System.out.println ("Start");


Long starttime = System.currenttimemillis ();


Arrayunique (array);


Long endtime = System.currenttimemillis ();


SYSTEM.OUT.PRINTLN ("Array Unique run Time:" + (Endtime-starttime) + "MS");





Long Starttimeb = System.currenttimemillis ();


Arrayunique (ARRAYB);


Long Endtimeb = System.currenttimemillis ();


System.out.println ("Arrayb Unique run Time:" + (ENDTIMEB-STARTTIMEB) + "MS");


}





public static double[] Arrayunique (double[] array) {


list<double> list = new arraylist<double> ();


for (int i = 0, j = array.length I < J; i++) {


if (!list.contains (Array[i])) {


List.add (Array[i]);


}


}


double[] Doubles = new double[list.size ()];


double[] Arrayunique = List.toarray (doubles);


return arrayunique;


}


}


Output:

Start
Array unique Run Time:577ms
Arrayb Unique Run time:5663ms




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.