Second week of Java learning (2)
array
The Concept of Container
Store multiple data together, and each data is called a container element.
// Water cup, wardrobe, classroom
Array: A container that stores a fixed length and guarantees a uniform type of all elements
Arrays are objects
Definition of arrays
1. Static binding
2. Dynamic binding
private static void guokexun() { //array int a=10; //static state int[] arr={1, 2, 3}; System.out.println(arr[0]); //dynamic int[] arr1=new int[5]; System.out.println(arr1[0]); arr1[0]=1; //The third way of definition is static binding int[] arr2=new int[]{1, 2, 3}; int[] arr3={2, 0, 1 ,9, 8, 8}; Arrays.sort(arr3); //Ranking from small to large System.out.println("Sorted arrays"); for (int i:arr3){ System.out.println(i); } }
Arrays are reference data types
private static void demo2() { String s1="guo"; System.out.println(s1); int[] arr1={1 ,2 ,3}; Person n1=new Person(); System.out.println(n1); }
Inheritance of arrays
Object is a superclass of all classes
Special cases:
Array types can be converted upwards to Object [], but the real parent class is actually Object.
private static void demo3() { String[] s1=new String[5]; //Upward transformation Object o=s1; Object[] o1=new Object[5]; System.out.println(s1.getClass().getSuperclass().getName()); Object[] o2=s1; }
Enhanced for cycle
private static void demo4() { int[] arr={12,22,11,99}; for (int i=0;i<4;i++){ System.out.println(arr[i]+" "); } System.out.println(); for (int i:arr){//Shortcut key iter System.out.print(i+" "); } }
Queries for Maximum and Minimum Values
private static void demo5() { int[] arr={99,22,77,1,55}; int max=0; int min=arr[0]; for (int i : arr) { if (i>max) max=i; } for (int i : arr) { if (i<min) min=i; } System.out.println("The maximum value is"+max); System.out.println("The minimum value is"+min); }
Array exchange order
private static void demo6() { int[] arr={33,21,45,22,13}; for (int min=0,max=arr.length-1;min<=max;min++,max--){ int temp=arr[min]; arr[min]=arr[max]; arr[max]=temp; } for (int i : arr) { System.out.println(i); } }
Digital memory
private static void demo7() { int i=1; i=i++; //i + + assigns value first in operation, such as a=i + +, assigns a=i first, then i=i+1, so the result is a==1 int j=i++; int k=i+ ++i*i++; //+ + I first calculates the assignment, such as a=++i, first calculates i=i+1, then assigns a=i, so the result is a==2 System.out.println(i+" "+j+" "+k);//i=4 j=1 k=11 }