Learning of Array class, Calendar class and System class

1. Array class

Arrays: Tool class for array operations (provides some sorting and binary search methods for arrays)
public static String toString(int[] a): can convert an array of int type into a string ([element 1, element 2, element 3...])
        public static void sort(int[] a) sorts the specified int array in ascending numerical order

public static int binarySearch(int[] a,int key): binary search method: find the index of the key element in an array of type int

public class ArraysDemo {
	
	public static void main(String[] args) {
		
		//Define an array: static initialization
		int[] arr = {24,69,80,57,13} ;
		
		//public static String toString(int[] a): You can convert an array of type int to a string ([element 1, element 2, element 3...])
		//Call directly with Arrays
		String str = Arrays.toString(arr) ;
		System.out.println("str:"+str);//[24, 69, 80, 57, 13]

		//public static void sort(int[] a) sorts the specified int array in ascending numerical order
		Arrays.sort(arr);
		String str2 = Arrays.toString(arr) ;
		System.out.println("str2:"+str2);
		
		//public static int binarySearch(int[] a,int key): binary search method:
		// Find the index of the key element in an array of type int
		//Requirement: Find the index corresponding to 57 elements
		Arrays.sort(arr);
		int index = Arrays.binarySearch(arr, 57) ;
		System.out.println("index:"+index);
		int index2 = Arrays.binarySearch(arr, 577) ;
		System.out.println("index2:"+index2);
	}
}
Let's analyze the source code of the toString method:
public static String toString(int[] a) {
        if (a == null) //Check if the array is not empty
            return "null";
        int iMax = a.length - 1; //arr.length-1   
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder(); //creates a string buffer
        b.append('['); //Append the left bracket first: [
        for (int i = 0; ; i++) {
            b.append(a[i]); //Append the elements in the array to the buffer
            if (i == iMax)
                return b.append(']').toString(); //return and append the closing bracket:] and convert the data element to a string
            b.append(", "); //If it is not the last index, then append a comma in the middle
        }
}

In the actual development process, as long as there is a reference type, when operating on the reference type data, the non-null judgment of the reference type object is performed to prevent NullPointerException (NullPointerException)

The source code of the binarySearch method:

public static int binarySearch(int[] a, int key) {
        return binarySearch0(a, 0, a.length, key);
    }
    
    /**
    	a--->arr: an array of the specified int type
    	fromIndex: start of specified index: 0
    	toIndex:arr.length 5
    	key: element value to find
    */
    	nt[] arr = {13,24,57,69,80} ;
     private static int binarySearch0(int[] a, int fromIndex, int toIndex,int key) {
        int low = fromIndex; //minimum index
        int high = toIndex - 1; // max index 4

        while (low <= high) { //if min index is less than= ​​max index  
            int mid = (low + high) >>> 1; >>> : unsigned right shift (bit operator) // middle index: mid = 2 ,3 ,4
            								Bit^: Bit XOR
            								Bit&: Bit AND
            								bit|: bit-or
            								<< : move left
            								There is a suitable data representation (original code, inverse code, complement code)
            								When the computer is operating at the bottom of the data: the operation is performed by complementing the code.
            int midVal = a[mid]; // Find the element corresponding to the middle index: arr[2] = 57 69 80

            if (midVal < key) //Judgment: compare the size of the element corresponding to the intermediate index with the value to be found
                low = mid + 1; //low = mid + 1; mid = (take the largest mid value) 4+1 = 5
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.    // return  -(low+1) = -6
    }

Here we mainly talk about unsigned right shift:

>> is a signed right shift

>>> is an unsigned right shift

Signed right shift is to convert the number to binary and then add 0 or 1 in front of it. If it is a positive number, add 0, and if it is a negative number, add 1

      For example , 11 >> 2, the number 11 is shifted to the right by 2

calculation process:

         The binary form of 11 is: 0000 0000 0000 0000 0000 0000 0000 1011, and then shift out the last two digits of the low order. Because the number is a positive number, zeros are added to the high order. The final result is 0000 0000 0000 0000 0000 0000 0000 0010. Converting to decimal is 2.

The difference between an unsigned right shift and a signed right shift is that the unsigned is always filled with 0

So the value of mid here is obtained by unsigned right shift in order of 2, 3, and 4.

2. Calendar class

Calendar class: Calendar class
Calendar class is an abstract class that provides some methods for converting between a specific instant and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, etc., and for manipulating calendar fields (such as getting the next week's date) Date) provides some methods
Note that the Calendar class is an abstract class, so how to instantiate it?

public static Calendar getInstance() : Create a calendar object through a static function

Common methods of the Calendar class:

public abstract void add(int field,int amount) According to the rules of the calendar, add or subtract the specified amount of time for the given calendar field 
public final void set(int year, int month, int date) Set the calendar fields YEAR, MONTH and the value of DAY_OF_MONTH

There is also a Date class that needs to be talked about in particular, and it is also a key point. We will talk about this next time.

Let's learn these methods of the Calendar class through a small example:

public class CalendarDemo2 {
	
	public static void main(String[] args) {
		
		// Calculate the current time
		Calendar c = Calendar.getInstance() ;
		//year
		int year = c.get(Calendar.YEAR) ;
		//moon
		int month = c.get(Calendar.MONTH) ;
		//day
		int date =  c.get(Calendar.DATE) ;
		System.out.println(year+"年"+(month+1)+"月"+date+"日");
		
		//Requirements: 10 days ago after 5 years
		c.add(Calendar.YEAR, 5);
		c.add(Calendar.DATE, -10);
		
		//get year
		year = c.get(Calendar.YEAR) ;
		date = c.get(Calendar.DATE) ;
		System.out.println(year+"年"+(month+1)+"月"+date+"日");

		//public final void set(int year, int month,int date) sets the values ​​of calendar fields YEAR, MONTH and DAY_OF_MONTH
		c.set(2018, 5,20);
		// get the year
		year = c.get(Calendar.YEAR);
		// get month
		month = c.get(Calendar.MONTH);
		// get day
		date = c.get(Calendar.DATE);
		System.out.println(year + "年" + (month + 1) + "月" + date + "日");
	}
}
So now there are the following requirements: Get how many days are in February in any year (keyboard to enter a year)


analyze:

1) Enter any year on the keyboard
2) Create a calendar class object
3) Set the year, month and day
set (enter year, 2, 1); //The actual date is March 1

4) Reuse add(int field,int amount) : here you only need to move the date forward by one day

public class CalendarTest {

	public static void main(String[] args) {
		
		//create keyboard input object
		Scanner sc = new Scanner(System.in) ;
		
		//Input data
		System.out.println("Please enter a year:");
		int year = sc.nextInt() ;
		
		//Create a calendar class object
		Calendar c = Calendar.getInstance() ;
		//set year month day
		c.set(year, 2, 1); //Actual March 1st
		//Just push the date forward by one day
		c.add(Calendar.DATE, -1);
		
		System.out.println("February has:"+c.get(Calendar.DATE)+"days");
	}
}

Third, the System class

The System class contains some useful class fields and methods. It cannot be instantiated. 
Commonly used methods:
public static void gc() to run the garbage collector. 
public static void exit(int status) terminates the currently running Java virtual machine. The parameter is used as the status code; in general, if the JVM needs to be terminated, then parameter 0

public static long currentTimeMillis() returns the current time in milliseconds

First create an entity class Person, in order to see the execution process of the garbage collector more intuitively, we rewrite the finalize method, because running the garbage collector actually executes the finalize method.

public class Person {
	
	private String name ;
	private int age ;
	
	public Person() {
		super();
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	

	@Override
	protected void finalize() throws Throwable {
		System.out.println("Start recycling unused objects:"+this);
		super.finalize();
	}
	
}
public class SystemDemo {
	
	public static void main(String[] args) {
		
		//Create an object of class Person
		Person p = new Person("Zhang San", 27) ;
		System.out.println(p);
		
		//Let the p object not specify heap memory
		p = null ;
		System.gc(); //Run the garbage collector, which is essentially the finalize() method executed
	}
}

Next, take a look at the exit method and learn how to terminate the Java virtual machine

public static void main(String[] args) {
		System.out.println("We like tall circles....");
		
		//public static void exit(int status)
		System.exit(0); //jvm has exited
		System.out.println("We also like starfruit....");
}

Running found that only the sentence "We like Gao Yuanyuan...." is printed, because the JVM has been terminated at this time.

currentTimeMillis() method:

public static void main(String[] args) {
		
		//public static long currentTimeMillis() returns the current time in milliseconds
		long time = System.currentTimeMillis() ;
		System.out.println("time:"+time);
		
		//Use alone, it doesn't make sense
		//Generally, to test the execution efficiency of a piece of code (behind: jdbc: PreparedStatement Statement can also use currentTimeMillis to test the rate)
		
		long start = System.currentTimeMillis() ;
		
		for(int x =0 ; x < 1000; x ++) {
			System.out.println("hello"+x);
		}
		
		long end = System.currentTimeMillis() ;
		
		System.out.println("Total time: "+(end-start)+"milliseconds");
}

arraycopy method:

        public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) copies an array from the specified source array, starting from the specified position and ending at the specified position in the destination array

src: original array
dest: destination array
srcPos: where to start from the original array
destPos: where to end in the destination array

length: length

public class SystemDemo2 {
	
	public static void main(String[] args) {
		
		int[] arr1 = {11,22,33,44,55,66} ;
		int[] arr2 = {5,6,7,8,9,10} ;
		
		System.out.println(Arrays.toString(arr1));
		System.out.println(Arrays.toString(arr2));
		System.out.println("---------------------------");
		
		System.arraycopy(arr1, 1, arr2, 2, 2);
		
		System.out.println(Arrays.toString(arr1));
		System.out.println(Arrays.toString(arr2));
		
	}
}

operation result:

[11, 22, 33, 44, 55, 66]
[5, 6, 7, 8, 9, 10]
---------------------------
[11, 22, 33, 44, 55, 66]

[5, 6, 22, 33, 9, 10]


Guess you like

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