Java array (personal note eight)

array

  1. Small Exercises and Array Definitions

    Write programs a b c and arrange them in descending order
public static void main(String[] args) {
int a = 90;
int b = 10;    
int c = 20;
int temp = 0;
if (a > b) {
temp = a;
a = b;
b = temp;
}
if (a > c) {
temp = a;
a = c;
c = temp;
}
if (b > c) {
temp = b;
b = c;
c = temp;
}
System.out.println("排完序以后:");
System.out.println(a);
System.out.println(b);
System.out.println(c);
}

   // Interview question: How to swap the values ​​of two int variables without a third temporary variable

public static void main(String[] args) {

int a = 10;

int b = 222;

a = a + b;

b = a - b;

a = a - b;

System.out.println(a);

System.out.println(b);

}

   Array: It is a container in which all elements of the same type are stored, and each element can be accessed using a subscript. The subscript starts from 0, which can be used for convenient query, sorting and other operations     
   . Definition of an array:
    element type[] array name=new element type[number of elements]
    int [] x =new int [10] ; //ok
    What type is x? Array type in reference type
    //Example, use subscripts to access elements in an array
    int [] x=new int [3]; //Create an array with a length of 3.
    The subscript of the array starts from 0
System.out.println(x[0]); //The default initial value of the int type is 0 
System.out.println(x[1]);
System.out.println(x[2]);
int [] x =new int [] {2,4,5} //ok when defining an array, initialize it directly. Be careful not to add numbers
int [] x =new int [3] {2,4,5} //error 
int [] x={2,4,6} //ok
cannot be written in the following way
int [] x=new int[3];
x={2,3,4} //error, can only be defined at the same time Initialization
The following is incorrectly written
int [3] x =new int [3] ; (the [] to the left of the equal sign cannot have a value)

Second, the characteristics of the array

1) Stack memory
     int [] a={1,5,9}; 
int [] b=a; 
a[1]=555; //The second element of a is changed, and it doesn't seem to have a dime relationship with b, but it will affect the array b
//Input array a
System .out.println("This is array a:");
for (int i = 0; i <3; i++) {
System.out.println(a[i]);
}
//Output array b
System.out. println("This is array b:");
for (int i = 0; i <3; i++) {
System.out.println(b[i]);
}
// After these two operations are completed, in the heap memory The {1,5,9} will become garbage
b= null; 
a= null;   
2) Subscript out of bounds exception 
   A subscript that does not exist in the accessed array will throw an exception 
   int [] a={1,5,9,10,20}; 
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]); //traverse java.lang.ArrayIndexOutOfBoundsException array index out of bounds exception
}
3) Null pointer exception 
Accessing a method or property of an object whose value is null, or an element or property of an array whose value is null, throws a
java.lang.NullPointerException

int [] a={1,5,9,10,20}; a=null;

a=null;

 int length=a.length; //Access the property whose value is a null array

   int value= a [2]; //For an array whose value is null, access its subscript 

Three, heap memory and stack memory

When a java program is running, it needs to allocate memory space. In order to improve efficiency, java classifies and manages the
memory == stack memory is
used to store local variables, when the variables are used up, the memory reclaims
the functions in java. When running, it will Apply for a block of memory space in memory, and then, the local variables declared in this function will allocate space from the
block space, and when the function ends, the space applied for by this function will be reclaimed, and all the space in this function will be reclaimed. The variables will also disappear. Of course, the memory
they occupy will also be released == heap memory    arrays and objects. Entities created with the new keyword are placed on the heap memory.    Each entity has a memory address value    entity that can be referenced The variables in , will have default initial values.    When the entity is no longer referenced, it will be reclaimed by the garbage collector at an indeterminate moment.




4. Small exercises on arrays

//Example 1, print all elements in the array
String[] nameList = new String[] { "赵明明", "高瑞", "王明", "张三" };
for (int i = 0; i < nameList.length; i++) {
System.out.println(nameList[i]);
}
System.out.println("-------------倒序输出--------------");
for(int i=nameList.length-1;i>=0;i--){
System.out.println(nameList[i]);
}
//Example 2, sum the elements in the array
  float [] array ={3.14f,  24,  25.5f, 66.89f}; 
  float sum=0;
  for(int i=0;i<array.length;i++){
  sum+=array[i];
  }
  System.out.println(sum); //119.53
   attached: int [] x={1,3,'A'}; //ok can compile and pass
//Example 3 spell the elements in the array into strings and return
public static void main(String[] args) {
int [] x={1,5,7,9,10}; 
String str="";
for(int i=0;i<x.length;i++){
//If not at the end, add "," to each
if(i!=x.length-1) {
str+=x[i]+"-";
} else{ //If at the end, Just don't add ","
str+=x[i]; 
}
}
System.out.println(str); //1-5-7-9-10
}
//Example 4 Get the largest element in the array
public class Test {
public static void main(String[] args) {  
int [] a={-4,-5,-1,-101,-8,-33,-99,-22};
int result= getMax(a);
System.out.println("数组中最大的是:"+result);  //-1
}
static int getMax(int [] x){
int max=x[0];
for(int i=0;i<x.length;i++){
if(max<x[i]){
max=x[i];
}
}
return max;
}
}

Fifth, the sorting of the array

    bubble 
    int [] a={2,5,7,1,6,3,9,5,11,7};
for(int i=0;i<a.length-1;i++){   //外循环 length-1
for(int j=0;j<a.length-1-i;j++) //内循环 length-1-i{
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
} } } for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" ,"); }




  
//The example encapsulates the sorting method into a function
public static void main(String[] args) {  
int [] a={2,5,7,1,6,3,9,5,11,7};
sort(a); 
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ,");
} } static void sort(int [] a) { //这个参数是引用类型 for(int i=0;i<a.length-1;i++){ for(int j=0;j<a.length-1-i;j++){ if(a[j]>a[j+1]){ int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } }











//Example, use the method provided by jdk to sort the array
java.util.Arrays.sort(a); //Positive sort

Six, the copy of the array

1) Copy with loop
   slightly
2) Use the classes provided by jdk
   == java.uitl.Arrays.copyOf(); //Note: it has a return value of type array
   //example
    int [] x  ={3,5,6,6,9,10} ;  
    int [] y=java.util.Arrays.copyOf(x, x.length); //this is a new array  
    Changes to elements in the new array will not affect the original array
   == System.arraycopy()  
     public static void arraycopy(Object src, //source array
                             int srcPos, //start from the first element in the target array
                             Object dest, //target array
                             int destPos, //start from the first element in the target array to put
                             int length) // a few elements to copy       
   //Example 
        int[] x ={3,5,6,6,9,10}; 
      int [] y=new int[x.length]; //Copy the above array into this array
    System.arraycopy(x, 0, y, 0, x.length);

Seven, one-dimensional array exercises

1 Declare an integer array of length 10, which stores 10 random numbers, and then sum these numbers
public static void main(String[] args) {  
//declare an array
int x[] =new int [10]; //initialize initArray(x) 
with random numbers ; showArray(x); // summation int result=sumArray(x); System.out.println( "Combination is"+result); } //Initialize with random numbers static void initArray(int [] x){ for (int i = 0; i < x.length; i++) { x[i]=(int)( Math.random()*10); } } // summation static int sumArray(int [] x){ int s=0; for (int i = 0; i < x.length; i++) { s+=x[ i]; } return s; } //Output the contents of the array static void showArray(int [] x){ for (int i = 0; i < x.length; i++) {























System.out.print(x[i]+"  ");
}

}

Eight, two-dimensional array

String [] x= {"aaa","bbb","3",null }; //All elements of the same type are stored in the array
int [] x={1,2,0,null}; //No Variables of basic data types, there is no value of null
int x=null;
char x=null;
boolean x=null; //These are all wrong
 
int [] x ={2,5};
int [] y ={ 5,8};
int [] z={2,6,7,9} ;
{x,y,z} //Each element is
a two-dimensional array in the array type java, which is an array of arrays
 
int [] [] array =new int [3][] ; //ok define a two-dimensional array, there are 3 elements in this two-dimensional array, the length of each element is uncertain
int [] [] array =new int [3] [5]; //ok has three elements, each element is an array of length 5
int [2] [] array =new int [2][] ; //wrong, no matter one-dimensional or two-dimensional array, as long as The value on the left side of the equal sign is wrong
int [] [2] array =new int [2][] ;
int [] [] array =new int [][]; //wrong
int [] [] array =new int [][3] ; // wrong
int [] [] array =new int [][]{{2,3},{6,9},{8,3,9}}; //ok at the time of declaration, initialize 
 
array[0][ 0]=100; //Assign the first element
array[2][2]=900; //Assign the last element
array[array.length-1][array[array.length-1].length -1] ; 
 
//How to traverse a two-dimensional array
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
System.out. print(array[i][j] +"\t");
}
System.out.println();
}
 
//Example
1 Sum up the contents of a two-dimensional array
public class Test {
public static void main(String [] args) {
int [] [] array =new int [][]{{2,3},{6,9},{8,3,999}}; 
int s= sum(array);
System.out. println("Combination is: "+s);
}
static int sum(int [] [] array ){
int s=0;
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
s+=array[i][j];
}
}
return s;
}
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325560785&siteId=291194637