Array of Java, looping

Source: Internet
Author: User
Tags decimal to binary

Break and continue use range:

Continue can only be used for looping structures, meaning that there must be loops as long as there is continue.

Break is used in switch statements and loop structures.

When break and continue exist alone, there can be no statement below because execution is not possible (error will be given)

function overloading (overload)

More than one function of the same name is allowed in the same class, as long as their parameter type/parameter number/parameter type order is different, regardless of the return type.

Arrays in Java:

First understand the following:

Some of the basic types of variables defined in the function (Short,int,char,long,double,byte,boolean,float), and the object's reference variable (int[] x, etc.) are allocated in the function's stack memory,

When a variable is defined in a block of code (that is, a bunch of curly braces {}), Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the variable

Allocated memory space, the memory space can be used for other purposes immediately.

Heap memory is used to hold objects and arrays created by new and to allocate memory in the heap, which is managed by the JVM's automatic garbage collector. After an array or object has been created in the heap, you can also define a special

Variable, so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object, which can then be used in the program to use the reference in the stack.

Variable to access an array or an object in the heap, the reference variable corresponds to a name (called a code line) that is an array or object.

A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed after the program runs outside its scope.

While the array and the object itself are allocated in the heap, the memory occupied by the array and the object itself is not freed, even if the program runs into a block of code that uses the new generated array and object statements, and the array and object are not referenced

When a variable points to it, it becomes garbage, can no longer be used, but still occupies the memory space, which is then taken away (released) by the garbage collector at an indeterminate time. This is also the reason why the Java comparison occupies memory.

The above excerpt from Zhang Xiaoxiang Teacher's <java employment Training course >

Example:

Int[] x;//defines an array x, the memory state of the statement after execution is as follows

x=new int [3];//array initialization, memory status as follows

Then test the default values for the various types of arrays:

Class Arraytest{public static void Main (string[] args) {//int,double,float,char type array default int[] n=new int[3];  SYSTEM.OUT.PRINTLN ("int" +n[1]);//0 char[] c=new char[3];   System.out.println ("char" +c[1]),//ascii code is 0 empty: ' f=new ' float[] [[]];   System.out.println ("float" +f[1]);//0.0f (plus F to indicate float type) double[] d=new double[3];   System.out.println ("Double" +d[1]);//0.0 boolean[] b=new boolean[3];   System.out.println ("boolean" +b[1]);//false}}   
Run Result: Two classic sort bubbles and selections: Example:
Import Java.util.*;class Sort {/* Bubble sorting: (from small to large, starting from 0 times for ease of operation) algorithm thought: Two adjacent number comparison, 22 compares obtains the larger number unceasingly moves, finally each trip maximum sink.                    Example: Subscript 0 1 2 3 4 I 5 3 7 9 1 3 5 7 9 1 5>3 Interchange 0th trip: 3 5 7 9 1 5<7 not moving   3 5 7 9 1 7<9 3 5 7 1 9 9>1 interchange-->9 for maximum, Arr[4] 9 total 4 (arr.length-0 (number of times)-1) round-trip: 3 5 7 1 -->9 do not participate in the comparison 3 5 7 1 3<5 not moving 3 5 7 1 5<7 not moving 3 5 1 7 7>1 switching-->7 for the second largest, arr[3] 7 for a total comparison of 3 (AR R.LENGTH-1-1) Two-order: 3 5 1-->7 No more participation in comparison 3 5 1 3<5 not moving 3 1 5 5>1 switching-->arr[2] for 5 comparison 2 (arr.length-2-1) Lam-rim three times: 3 1-->5 do not participate in the comparison 1 3 3>1 Exchange-->arr[1] 3 for a total comparison of 1 (arr.length         -3-1) A total of 4 (arr.length-1) trip last must have left a number 1, no longer participate in the comparison, certainly minimum *//Exchange public static void Swap (int[] B,int I,int j) {         int temp=b[i];         B[I]=B[J];      B[j]=temp; }//bubble sort public static void Bubblesort (int[] a) {for (int i=0;i<a.length-1;++i)//control trip number foR (int j=0;j<a.length-i-1;++j)//control the number of times per trip comparison if (a[j]>a[j+1]) swap (a,j,j+1);   }/* Select Sort: (from small to Large) algorithm idea: Each trip selects the smallest (or largest) element from the data element to be sorted, placing the order at the end of the ordered sequence until all the data elements to be sorted are exhausted.                    Example: Subscript 0 1 2 3 4 5 3 7 9 1 I 3 5 7 9 1 5>3 Interchange 0th trip: 3 5 7 9 1 3<7 not moving                  3 5 7 9 1 3<9 not moving 1 5 7 9 3 3>1 swap-at this time arr[0] is 1 and the smallest total comparison 4 (arr.length-0-1) times 5 7 9 3 5<7 First trip: 5 7 9 3 5<9 not moving 3 7 9 5 3<5 Swap--at this time arr[1] is 3, minor total comparison 3 (arr.lengt       H-1-1) Two-stage: 7 9 5 7<9 not moving 5 9 7 5<7 Swap--at this time arr[2] is 5.      Compare 2 (arr.length-2-1)-Order three times: 7 9 9>7 Swap--at this time arr[3] is 7. A total of 1 (arr.length-3-1) took a 4 (arr.length-1) trip, the last remaining 9, for the largest, arr[4] for 9 * *//select sort public static void SE Lectsort (int[] b) {for (int i=0;i<b.length-1;++i)//Control trip number for (int j=i+1;j<b.length;++j)//comparison (ARR.LENGTH-1)-(i+1)              +1 if (B[i]>b[j])  i.e. Arr.length-i-1 swap (B,I,J);}   Select sort second notation: public static void Selectsort_2 (int[] c) {int k=0;        for (int i=0;i<c.length-1;++i) {k=i;        for (int j=i+1;j<c.length;++j) if (c[k]>c[j]) k=j;      if (k!=i) swap (c,k,i); }}/* this type of notation and the above is the biggest difference is: K in each of the smaller elements of the subscript, until a trip to the end of the K store this trip the smallest element subscript at this time in and the first position of the element exchange *//print array public static void Showarray (int[] arr) {System.out.print ("[");         for (int i=0;i<arr.length;++i) if (i!=arr.length-1) System.out.print (arr[i]+ ",");    ElseSystem.out.println (arr[i]+ "]"); }//test public static void Main (string[] args) {int[] arr={7,3,9,11,1,6,5};int[] arr_2={6,2,3,1,11};int[] arr_3={9,8,10 , 2,11,3};bubblesort (arr);    System.out.println ("Bubblesort:"); Showarray (arr); Selectsort (arr_2);       System.out.println ("Slectsort:");       Showarray (arr_2); Selectsort (arr_3);    System.out.println ("selectsort_2:");  Showarray (arr_3);//arrays.sort (arr_2);//showarray (arr_2) used in actual development;}   }
Operation Result:

Maximum and minimum values:

Class  maxmin{//is equivalent to bubbling/selecting the sort of a trip//can be traversed at the same time to find the maximum and minimum value public   static void Main (string[] args)   {     int max, min;     Int[] arr={3,2,1,6,9,5}; The initial value of Max=min=arr[0];//max and Min can be an array of any two values, but the following loop must start with subscript 0 (i=0) for     (int i=1;i<arr.length;++i)       if (Arr[i] >max)       Max=arr[i];       else            if (arr[i]<min)      min=arr[i]; System.out.println ("max=" +max+ ", min=" +min);}   }
Operation Result:

Binary (two-point search):

Example:

Class Bisearch {/* binary (binary) lookup: algorithm idea:  requires sequence must be ordered (ascending/descending), because only in order to determine  the scope of the data, through constant binary to narrow the scope of the lookup data  to find the data is key  ① specifies the range of data by two variables min and max, requiring Min<=max         (Min=max indicates only one data)  ② first compared to mid= (Min+max)/2, if Key=mid lookup succeeds, returns     directly Mid, if Key<mid, then min=mid-1, shorten the look-up range, at which point the key is compared with mid= (max+min)/2, if key>mid, then max=mid+1, and then compare with the new mid, and so on to find the return, Not found then min>max.*/public static int Bisearch (int[] arr,int key) {  int max=arr.length-1,min=0,mid;  while (max>=min)  {   mid= (max+min)/2;   if (Key==arr[mid]) return  mid;//returns a key in the array of the subscript   else if (Key<arr[mid])           max=mid-1;     else   min=mid+1;  }       return-1;//= not Found} public  static void Main (string[] args)  {    int[] arr={3,5,7,9,10,11}; System.out.println ("keyindex=" +bisearch (arr,11));}  }

Binary lookup process (for example above)

Find success:

Example 2:

An ordered array is known to require that an element be inserted in an ordered array to make it still orderly.

The 
 class bisearch_2{//an ordered array, requiring an element to be inserted in an ordered array, so that it is still ordered/* thought: ① First we need to find the position where the element is inserted in order to operate ② because the array is ordered, binary find to determine its location ③ place the position (including this bit The elements (from the back forward) are moved backward, one position is vacated for the newly inserted element */public static int Bisearch (int[] arr,int key) {int Max=arr.length-2,min=0,mi  D   while (max>=min) {mid= (max+min)/2;     if (Key==arr[mid]) return mid;//returns a key in the array of the subscript else if (Key<arr[mid]) max=mid-1;  else min=mid+1; The return min;//is determined by the figure that min is the insertion position of the element}//The element in the array is moved back, that is, the assignment process public static void backward (int[] arr,int site,int key)//   Site is the insertion position {int i;   for (i=arr.length-2;i>=site;--i)//Example: Site=3,arr.length=7 arr[i+1]=arr[i]; arr[i+1]=key;//at this time i=2, so the insertion position is i+1} public static void Main (string[] args) {int[] arr={3,5,7,9,10,11,0};//known quantity Group of meta The element is 6, the last 0//in order to let the array to open up a space, storing the inserted elements int index;index=bisearch (arr,8);  System.out.println ("keyindex=" +index); backward (arr,index,8);//print for (int i=0;i<arr.length;++i)  System.out.print (arr[i]+ ""); }}
Operation Result:
Lookup process:
Note: Binary find the advantage is less than the number of comparisons, Find Fast, average performance is good;
The disadvantage is that it requires the unknown origin table to be an ordered table, and insert Delete is difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent.
Binary conversions:
   ① decimal to binary (except for the second method, only for positive numbers)
Class arraytest_2{  //decimal to Binary/  *   algorithm idea:     ① use 2 to take the remainder of the method ② take into account that the     reverse output can be used in the sequential stack (LIFO) mode output */   public static void Tobi (int number)  {    int[] stack=new int[32];    int top=-1;//stack top pointer (similar to pointer function) while (number!=0) {  stack[++top]=number%2;  number/=2;}    while (TOP!=-1)//Out Stack System.out.print (stack[top--]);  }  Method two, using the method provided in Java public   static void tobi_2 (int number)  {     stringbuffer sb=new stringbuffer ();// A container with data is defined     while (number!=0) {  sb.append (number%2);//Add number/=2 to the container  ;} System.out.print (Sb.reverse ());//through reverse function in StringBuffer   //Reverse output  } public    static void  Main ( String[] (args)    {    Tobi);    System.out.println ();    Tobi_2 ();  }  /*   The method can only calculate positive numbers  */}
② decimal to hexadecimal (using SHIFT and bitwise VS)
     
Class tohex{//decimal-to-hexadecimal//   algorithm thought:     ① first the number with the lower four bits is 1, the remaining bits 0 (15) and the number of (&) can be obtained the number of low four bits ② make the number right shift (>>>) four bits, In the 15 phase and get four bits, and so on know that the        original number becomes 0 stop note: Here >>> without >> because the negative number will always be 1,      of course, can pass-1 (full complement of 1) to determine the end, but cannot output  The sign bit is hexadecimal, and >>> can turn the sign bit of negative number to  hex *  /public static void Tohex (int number)  {     StringBuffer sb= New StringBuffer ();//defines a container for data storage int Hex;     while (number!=0)//for (int i=0;i<8;++i)//force the conversion of 32 bits: 200->0000c8{                    //While the while is: C8  hex=number&15;  if (hex>=10) sb.append ((char) (hex-10+ ' A '));   else Sb.append (HEX);  Number >>>= 4;} System.out.print (Sb.reverse ());  }    public static void  main (string[] args)    {    Tohex (-200); System.out.println ("\ n" +integer.tohexstring ( -200));}  }
③ Decimal to R-System (table-checking method)
Class convert{//Tabular converts decimal to R (two, eight, 16)/* Array subscript: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 A B C D E F includes a binary, octal, hexadecimal value that corresponds exactly to the subscript of the array.   *////binary public static void tooct (int number) {trans (number,1,1);   }//Eight binary public static void Tobi (int number) {trans (number,7,3);   }//16 binary public static void Tohex (int number) {trans (number,15,4); } public static void trans (int number,int and,int offset)//receive the original number separately, need the value with,//need to shift the value {if (number==0)//to 0 below is not executing {Syst  EM.OUT.PRINTLN (0); return;  } char[] table={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};  Char[] Stack=new char[32];  int top=-1; while (number!=0) {Stack[++top]=table[number & and]; Number >>>= offset;} while (Top!=-1) System.out.print (stack[top--]);                                                            System.out.println ();}      public static void Main (string[] args) {Tobi (-80);      Tohex (-80);   TOOCT (-80); }}
Two-dimensional arrays:
In Java there is no real multidimensional array, only an array of arrays, though the application is much like
A multidimensional array in C, but there is still a difference. Defining a two-dimensional array in the C language must be
is a x*y two-dimensional matrix block.
Multidimensional arrays in Java are not necessarily matrix forms of rules
Define a multidimensional array:
Int[][] Xx;//int xx[][],int[] xx[];
An array reference variable XX, the first element variable is xx[0], the nth element variable is xx[n-1].
Each element variable in XX (Xx[0]~xx[n-1]) is exactly an array reference variable of an integer type.

int[[] xx;
Xx=new int[3][];
parsing: these two codes indicate that the array xx has three elements, and each element is a one-dimensional array of type int[]. Equivalent to three arrays defined

Reference variables, respectively:int[] xx[0],int[] xx[1],int[] xx[2].

Because xx[0],xx[1],xx[2] are array reference variables, they must be assigned to a real array object. You can refer to the values in these arrays

Elements.

Xx[0]=new Int[3];

Xx[1]=new int[2];

Other:

Static initialization of two-dimensional arrays:

Int[] [] xx={{3,2,7},{1,5},{6}};

Also attached Chen Gishan classmate of the summary of the Java array, personally think very good: http://bdcwl.blog.163.com/blog/static/7652226520091024067604/

Example 1:

Class ArrayDemo1 {public    static void Main (string[] args)     {        int[] arr = new int[2];//recommend this way to define a reference variable a for an int type array RR                int arr[] = new int[2];        Static initialization        int[] arr = new Int[]{3,1};//new int[] Cannot specify length, compilation cannot pass                                       //may occur with different number of elements and specified length            int[] arr = {3,1};// Static initialization simplified form        System.out.println (arr[3]);//compile can pass, compile time does not create an array that is in the run time in the heap memory to open up space for the array.                                   In the run time, the array angle mark crosses the anomaly        Arr=null;        System.out.println (arr.length);//compilation can still be passed, for the same reason.                                An error occurred during runtime, arr no longer references an array, cannot manipulate elements in array                               //emit null pointer exception               //two-dimensional array static initialization            int[][]a=new Int[][]{{4,2},{5,6,7}};//①        //int[][]a={{4,2},{5,6,7}};//equivalent to ①      }}
Example 2:
Class  doublearray{public    static void Main (string[] args)     {        int[][] xx=new int[3][2];//three elements in a two-dimensional array, Each element points to a one-dimensional array of length 2
        System.out.println ("x\t" +xx),//[[represents a two-dimensional array, i->integer (shaping), and the element type//@ in the array is                         followed by a hash function to calculate the hash address        System.out.println ( "X[0]\t" +xx[0]);                        Int[][] Y=new int[4][];                         System.out.println ("y\t" +y);        System.out.println ("y[0]\t" +y[0]);                 Int[][] X=new int[3][];//The length of each reference array can be different                x[0]=new int[3];      In-memory situations such as:        x[1]=new int[1];        X[2]=new int[2];}            }

The two-dimensional array is in memory:

Array of Java, looping

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.