Reference type--java Array

Source: Internet
Author: User
Tags array length sorts ruby on rails

Array:
a set of related data, in fact, is a series of variables, can be divided into: one-dimensional array, two-dimensional array, multidimensional array default value is NULL, there is no point to the memory space in Java the array must be initialized before it can be used.
The so-called initialization is to allocate the memory space for array elements of arrays and assign an initial value to each array element.
First, array initialization
1, static initialization static initialization: When initialized, the programmer explicitly specifies the initial value of each array element, and the system determines the desired array length. Static initialization Syntax Format:
arrayname=new type[]{element1,element2,element3,element4 ...};
Type: The data type of the array element, where the type must be the same as the type used when defining the array variable, or a subclass of the type used to define the array, and enclose all array elements with curly braces, separated by commas (,), and the curly braces that define the initialization values follow [ After code example:
//Define a variable of type int array, variable named intarrint[] intarr; //declares a one-dimensional array //uses static initialization, initializes the array with only the initial value of the array element specified, and does not specify the array length. Intarr=new int[]{5,6,8,20};//defines a variable of type Object array, the variable named objarrobject[] objarr;//uses static initialization, When an array is initialized, the type of the array element is a subclass of the array element type when the array is defined objarr=new string[]{"java", "Li Gang"};object[] objarr2;//use static initialization objarr2=new object[]{"Java "," Carp "};
Arrayname={element1,element2,element3,element4 ...} code example:
int scorep[]={23,56,89,75,68}; Array declaration with initial value
2, dynamic initialization dynamic initialization: The programmer only specifies the length of the array when initializing, and the system assigns the initial value to the dynamic initialization syntax format for the element elements:
Arrayname=new Type[length]; //Allocate memory to array length specifies the size of the array, that is, the number of array elements that can be accommodated.
code example:
The
definition and initialization of the array is done at the same time, using the dynamic initialization syntax int[] prices=new the definition and initialization of the int[5];//array is done at the same time, the type of the element when initializing the array is the subclass of the element type when the array is defined. Object[] Books=new string[4];
When you specify an initial value, the system assigns the initial value as follows:
(1) The type of the array element is the integer type in the base type (byte, short, int, and long), the value of the array element is 0. (2) The type of the array element is a floating-point type (float, double) in the base type. The value of the array element is 0.0. (3) The type of the array element is the character type (char) in the base type, and the value of the array element is ' \u0000 '. (4) The type of the array element is a Boolean type (Boolean) in the base type. The value of the array element is false. (5) The type of the array element is a reference type (class, interface, and Array), and the value of the element is null.
Attention:
do not use static initialization and dynamic initialization at the same time. Arrays can be used after initialization of the array.
Second, use the array
The
most common use of arrays is to access array elements, including assigning and accessing the values of array elements. The Java language array index starts at 0, the first array element has an index value of 0, and the last array element's index is reduced by 1. The code is as follows:
//Output Objarr The second element of the array, the output string "Li Gang" System.out.println ( OBJARR[1]);//Assign a value objarr[0]= "Spring" for the first array element of OBJARR2, or if the index specified when accessing an array element is less than 0 or greater than or equal to the length of the array, the compiler will not have any errors. The runtime exception occurs: Java.lang.arrayindexoutofboundsexception:2 (array index out-of-bounds exception), an int integer after the exception prompt, which is the array index accessed by the programmer view. code example://access array element The specified index is equal to the array length, so the following code will appear at run time exception System.out.println (objarr2[2]);
iterate through an array:
//Use the value of the loop output Pricese array for each array element for (int i=0;i<prices.length[i];i++) {System.out.println (prices[i]);}
Third, Foreach Loop
from JDK1.5, Java provides a simpler loop: The Foreach loop, which iterates through arrays and collections more succinctly. Syntax format for the Foreach Loop: For
(Type Variablename:array | collection) {//variablename automatically iterates over each element ...} The type of the array element or collection element, the VariableName parameter name, and the Foreach loop automatically assigns the array element, the collection element, to the variable sequentially.
code example:
string[] books={"lightweight Java ee", "authoritative guide", "Ajax Treasure Book"};//use a Foreach loop to iterate over an array element, where book will automatically iterate over each array element for (String book:        Books) {//Use a Foreach loop to iterate over the output array element or collection element, usually do not assign a value to the loop variable//book= "Ruby on Rails Agile development Best practices"; SYSTEM.OUT.PRINTLN (book);}
Note:
when using a Foreach loop to iterate over an algebraic group element, you cannot change the value of an array element, so do not assign a value to a foreach loop variable.
Four, the operation mechanism of array in memory
1, array of running media
An array is a reference data type, and an array drinking variable is simply a reference, and array elements and arrays of variables are separated in memory. The actual array elements are stored in heap memory, and the array reference variable is a reference-type variable that is stored in stack memory.
Why is there a stack of memory and heap memory points? When a method executes, each method builds its own memory stack, and the variables defined in the method are placed in the stack memory one by another, and as the method executes, the memory stack of the method is destroyed. Therefore, all variables defined in the method are placed in the stack memory, and when we create an object in the program, the object is saved in the runtime data area for reuse (because object creation costs are usually large), the runtime data area is heap memory. The exclusive use of heap memory is not destroyed by the end of the method, even if the object may be referenced by another reference variable at the end of the method, the object will still not be destroyed. The garbage collection mechanism of a system reclaims a object only when it is not referenced by any reference variable. code example:
//define and initialize the array, use static initialization int[] a={5,7,20};//define and initialize the array, use dynamic initialization int[] b=new int[4];//output B array length System.out.println (" The length of the B array is: "b.length);//loop output a array of elements for (int i=0;i<a.length;i++) {System.out.println (a[i]);} Loop output b array of elements for (int i=0;i<b.length;i++) {System.out.println (b[i]);} Because A is a int[] type and B is a int[] type, you can assign the value of a to b//, which is to let the B reference point to the array that the a reference points to b=a;//re-output the length of the B-array ("B-array Length:" System.out.println);
Operation Result:
the length of the B array is: 457200000b the length of the array is: 3
After defining and initializing an array, two spaces are allocated in memory, one for storing the reference variable for the array, and one for storing the array itself. When A and B two arrays are defined and initialized by the program, the system memory actually produces 4 blocks of memory, with two reference variables in the stack memory: A and B, and two blocks of memory in the heap memory, respectively, for storing the array to which the A and B references refer. The memory is stored as shown in the following:

When b=a the code, the system assigns the value of a to both B,a and B as reference type variables and stores the address. So assigning the value of A to B means that B points to the address pointed to by a. At this point, the memory of the computer is stored as follows: When B=a is executed, the first array in heap memory has two references: a variable and b come to the first array.
At this point the second array loses its function, becomes garbage, and only waits for a garbage collection to reclaim it--but its length remains unchanged until it disappears completely.
2, initialization of a primitive type array for a primitive type array, the value of the array element is stored directly in the corresponding array element, so when the array is initialized, the array is assigned a memory control, and the value of the array element is then stored directly in the corresponding array element. The code examples are as follows:
Defines an array constant of type int[] int[] Iarr; Only one array variable is defined at this time the memory is as follows:
Dynamically initialize an array with an array length of 5iarr=new int[5]; after dynamic initialization, the system is responsible for allocating memory space for the array and assigning default initial values: All array elements are assigned 0, at which time the memory is stored as:
Use loop to assign values for each array element for (int i=0;i<iarr.length;i++) {iarr[i]=i+10;} when the loop assigns a value to each array element in the array, the value of each array element becomes the program-developed value. When you explicitly set the value of an array element, it is stored as follows: from which you can see the storage of an array of primitive types, the values of each array element are stored directly in the corresponding memory.
When manipulating an array element of an array of basic data types, it is actually a variable that operates on the underlying type.
3, initialization of a reference type array
An array element of a reference type array is a reference: Each array element is stored or referenced, and it points to another piece of memory, which stores valid data.    Class person{//Age public int ages;    Height public double height;    Define an info method public void info () {System.out.println ("My Age is:" +age+ "My height is:" +height); }}
Defines a students array variable whose type is person[]person[] students; // This line of code simply defines a reference variable in the stack memory, which is a pointer that does not point to any valid memory area. The memory is now stored as follows:
Perform dynamic initialization of students =new PERSON[2]; //
Create a person example and assign the person example to the Zhang Variable person zhang=new person (), or//To assign a value to the property of the person object referenced by Zhang Zhang.age=15;zhang.height =158;//creates a person example and assigns the person instance to the Lee variable perosn lee=new person ();//assigns a value to the property of the person object referenced by Lee lee.age=16;lee.height=161 ;//Define two person instances, define these two instances to actually allocate 4 blocks of memory, store the Zhang and Lee two reference variables in the stack memory, and store two person instances in the heap memory. The memory storage at this point is as follows:
Assigns the value of the Zhang variable to the first array element students[0]=zhang;//assigns the value of the Lee variable to the second array element students[1]=lee;//when the program Zhang Yi to the first element of the students array, To assign Lee to the second element of the students array, the two array elements of the students array will point to a valid memory area. The memory storage is as follows: From the image above you can see that both Zhang and Students[0] point to the same memory area, and they are all reference type variables, so accessing the properties and methods of the person instance via Zhang and Student[0] is exactly the same, Whether you modify the properties of the person instance pointed to by the students[0] or modify the properties of the person instance that the Zhang variable points to, the same memory area is modified, so it is bound to affect each other. Similarly, Lee and Students[1] have the same effect.
The following two lines of code result in exactly the same as Lee and Students[1] point to the same person instance lee.info (); Students[1].info (); Run Result:
my age is: 16 my height is: 161.0 my age is: 16 my height is: 161.0
V. Tool classes for manipulating arrays
java.util.Arrays
The Java-provided arrays class contains some static modified methods that can manipulate the array directly, and the arrays class contains several static modifiers (static-modified methods can be called directly from the class name).
BinarySearch (type[] a,type key):
The
index of the key element value in the A array is queried using the binary method, and a negative number is returned if the a array does not contain the key element value.
Calling this method requires that the elements in the array are already ordered in order for the correct result to be obtained.
BinarySearch (type[] array, int fromIndex, int toindex, type value):
similar to the previous method, but it searches only the elements of the Fromindex to Toindex index in the A array.
Calling this method requires that the elements in the array are already ordered in order for the correct result to be obtained.
CopyOf (type[] original, int newlength):
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 preceding element of the new array is all elements of the original array, supplemented by 0 (numeric), False (Boolean), or null (reference type).
Copyofrange (type[] original, int from, int. to):
This method is similar to the previous method, but this method only copies the from index of the original array to the elements of the to index.
Equals (type[] array1, type[] array2):
This method returns true if the length of the array1 array and the array2 array are equal, and the array1 array and the array element one by one of the array2 array are the same.
Fill (type[] array, type value):
This method assigns the value of all elements of the A array to value.
Fill (type[] array, int fromIndex, int toindex, type value):
This method is similar to the previous method, except that the method assigns value to the array element fromindex to Toindex index only.
Sort (type[] array):
the method sorts the array elements of a group array.
Sort (type[] array, int fromIndex, int toindex):
This method is similar to the previous method, except that the method sorts only the elements that are indexed fromindex to Toindex.
ToString (type[] array):
The method converts an array into a string. This method concatenating multiple array elements together in order,
Multiple array elements are separated with commas (,) and spaces.
code example:
//Define an An array of int[] a=new int[]{3,4,5,6};//define a a2 array int[] a2=new int[]{3,4,5,6};//a array and A2 array are equal in length, each element is equal in sequence, The output trueSystem.out.println ("a array and A2 array are equal:" +arrays.equals (A,A2));//By assigning a array of a, a new B-array int[] b=arrays.copyof (a,6); System.out.println ("a array and A2 arrays are equal:" +arrays.equals (A, b)); The elements of the B array are: "+arrays.tostring (b));//Assign the 3rd element of the B array (including) to the Fifth Element (not included) to 1arrays.fill (b,2,4,1);//output b array element, output {3,4,1,1,0,0} System.out.println ("element of array B is:" +arrays.tostring (b));//Sort B array Arrays.sort (b);//output b array element, output {0,0,1,1,3,4} System.out.println ("The elements of array B are::" +arrays.tostring (b));
Operation Result:
A and A2 arrays are equal: The Truea array and the A2 array are equal: The elements of the FALSEB array are:: [
3, 4, 5, 6, 0, 0]b the elements of the array are:: [3, 4, 1, 1, 0, 0]b the elements of the array are:: [0, 0, 1, 1, 3, 4]
In order to use the arrays class in your program, you must import the Java.util.Arrays class in your program. One method of the system class: static void Arraycopy (Object arc,int srcpos,object dest,int destpos,int length):
This method assigns the element value in the SRC array to the elements of the dest array, where srcpos specifies to start copying from the first element of the SRC array,
The length parameter specifies how many elements of the SRC array are assigned to the elements of the dest array.
Vi. Other
array name of the two-dimensional array data type []=null; Declares a one-dimensional array array name =new data type [number of rows] [number of columns];//Allocate memory to array multidimensional array int a[][][][]=new int[][][][];

code example:
Public class javaarray {    public static void main (String  args[])     {        //one-dimensional array          int score[]={52,1,26,89,75,5,6,78,90,23};         int max=0;        int min=0;         max=min=score[0];        for  (int i = 0; i < score.length; i++)  {             if (Score[i]>max)              {                 max=score[i];            }      &nBsp;      if (score[i]<min)              {                 min=score[i];            }   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Maximum value: "+max");         system.out.println ("Minimum Value:" +min);
Dynamic definition int a[]=new int[3];        a[0]=3;        a[1]=3;        a[2]=3;        for (int i = 0; i < a.length; i++) {System.out.print (score[i]+ "\ t"); }
System.out.println ();
        //to sort the array         for   (int i = 1; i < score.length; i++)  {             for  (int j = 0; j <  score.length; j++)  {                 if (Score[i]<score[j])                  {                     int temp=score[i];                     score[i]=score[j];                      Score[j]=temp;                }             }        }         for  (int i = 0; i < score.length;  i++)  {            system.out.print ( score[i]+ "\ t");         }
        //two-dimensional array         int  aEr[][]=new int[4][3];         aEr[0][0]=30;         aer[1][1]=28;        aer[0][ 2]=45;        aer[2][0]=28;         aEr[3][2]=8;        for  (int i = 0; i  < aer.length; i++)  {             for  (int j = 0; j < aer[i].length; j++)  {                 system.out.print (AEr[i][j] + "\ T");            }          &Nbsp;  system.out.println ("");        }     }}


Reference type--java Array

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.