JavaSE——day11Arrays、Calendar、System、Date、Math、Random类

Arrays类

   The following content is from JDK1.6.0!
       The Arrays class package is java.util.Arrays and inherits from java.long.Object. The methods in the Arrays class are all static methods.
    This class contains various methods for working with arrays (including binary search, copying a specified array, checking whether two arrays are equal, quicksort, returning a string, returning a hash code based on the contents of the specified array, converting the specified boolean value is assigned to each element of the specified boolean array). This class also contains a static factory that allows the array to be viewed as a list.
    This class is a member of the Java Collections Framework .

    binary search

  Method summary:      
static int binarySearch(byte[] a, byte key)
          Use the binary search method to search the specified byte array to obtain the specified value.
static int binarySearch(byte[] a, int fromIndex, int toIndex, byte key)
          Use the binary search method to search the range of the specified byte array to obtain the specified value.

    About binary search:
        The binary search method in the Arrays class has only these two formats, but the searched array is not only of byte[] type, but also of char[], double[], float[], int[], long[], short[] , Object[], and the generic T.

     toString method

    The toString method inherits from the Object class under the long package.
Method summary:

    

static String toString(int[] a)
          Returns a string representation of the contents of the specified array.
     About toString:
                The formal parameters of this method can also be: boolean[],float[],double[],char[],byte[],Object[],long[],short[], the return is a String string.

      sort quick sort method

   Method summary:
        
static void sort(byte[] a)
          Sorts the specified byte array in ascending numerical order.
static void sort(byte[] a, int fromIndex, int toIndex)
          Sorts the specified range of the specified byte array in ascending numerical order.
      About sort:
                The quick sort method in the Arrays class has only these two formats, which are suitable for 7 common types + generic + Object type as formal parameters.

       


Other methods:


     The equals method is suitable for the equality judgment of 7 kinds of +Object type arrays, because the source code rewrites the toString method, so the array elements are compared. Method summary:

            

static boolean equals(int[] a, int[] a2)
Returns true           if the two specified arrays of int are equal to each other .
    The fill method is used to replace all elements in the array or the specified range of elements with a value. This value can be of 7 +Object types, and the replacement value must be consistent with the array type. Method summary:
static void fill(boolean[] a, boolean val)
          Assigns the specified boolean value to each element of the specified boolean array.
static void fill(boolean[] a, int fromIndex, int toIndex, boolean val)
          Assigns the specified boolean value to each element in the specified range of the specified boolean array.

      Summary of hashcode method:
static int hashCode(boolean[] a)
          Returns a hash code based on the contents of the specified array.
example:
import java.util.Arrays;

public class Test {
	
	public static void main(String[] args) {
		int[] arr = {21,32,14,56,32,10};
		
		//toString method
		String str = Arrays.toString(arr);
		System.out.println("String:"+str);
		
		// binary search method
		int index = Arrays.binarySearch(arr, 32);
		System.out.println("index:"+index);
		
		//sort quick sort
		Arrays.sort(arr);//The return value of quick sort is void, and the result cannot be received! !
		printArray(arr);
		
		//fill replacement method
		Arrays.fill(arr, 32);//Replace all elements with 32
		printArray(arr);
		
		//hashcode method
		int hash = Arrays.hashCode(arr);
		System.out.println("hashcode: "+hash);
		
		//equals method
		int arr2[] = {21,32,14,56,32,10};
		System.out.println(Arrays.equals(arr, arr2));//Because the sort and fill methods both directly change the value of arr[], they are not equal
		int arr3[] = {32, 32, 32, 32, 32, 32};
		System.out.println(Arrays.equals(arr, arr3));
	}
	//traverse
	public static void printArray(int[] arr) {
		
		System.out.print("result:[");
		for(int x = 0 ;x <arr.length ; x++) {
			if(x == arr.length-1) {
				System.out.println(arr[x] + "]");
			}else {
				System.out.print(arr[x]+", ");
			}
		}
	}

}

Calendar class

    The Calendar class is an abstract class (public abstract class Calendar extends Object), which 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 date of the next week) ) provides some methods. An instant can be expressed as a millisecond value, which is an offset from an epoch (ie, 00:00:00.000 GMT, January 1, 1970, Gregorian calendar).

static Calendar getInstance()
          Get a calendar with the default time zone and locale.
static Calendar getInstance(Locale aLocale)
          Gets a calendar with the default time zone and the specified locale.
static Calendar getInstance(TimeZone zone)
          Get a calendar with the specified time zone and default locale.
static Calendar getInstance(TimeZone zone, Locale aLocale)
          Get a calendar with the specified time zone and locale.

        The constructors of the Calendar class are all protected, so only subclasses can be instantiated. Because Calendar is an abstract class, it cannot be instantiated. So how to instantiate it? The Calendar class provides a static method: getInstance(), which returns a Calendar object.
 int get(int field)
          Returns the value of the given calendar field.

        To use a field to get the current date, you must use the get method to get the value of the field.


 
 
 
import java.util.Calendar;

public class Test2 {
	public static void main(String[] args) {
		
		//set up Calendar Object
		Calendar calendar = Calendar.getInstance();
		
		//get year,month,day
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DATE);
		System.out.println(year+"-"+(month+1)+"-"+day);
		
		//Calendar change:add method
		calendar.add(Calendar.YEAR, 2);
		year = calendar.get(Calendar.YEAR);
		calendar.add(Calendar.DATE,2);
		day = calendar.get(Calendar.DATE);

		System.out.println(year+"-"+(month+1)+"-"+day);
	}
}

Two common methods in Calendar:
 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 (this method is commonly used) public final void set(int year, int month, int date) set Values ​​of calendar fields YEAR, MONTH, and DAY_OF_MONTH
import java.util.Calendar;

public class Test3 {
	public static void main(String[] args) {
		Calendar c = Calendar.getInstance();
		c.set(2018, 8, 8);
		
		//Because the return value of the set method is void, only the year, month, and day can be obtained separately
		int year = c.get(Calendar.YEAR);
		int month  = c.get(Calendar.MONTH);
		int date  = c.get(Calendar.DATE);
		System.out.println(year+"-"+month+"-"+date);
	}
}
example:
import java.util.Calendar;
import java.util.Scanner;

/**
 * Requirement: Get how many days are in February in any year (Improvement: Enter a year on the keyboard)
 */
public class Test4 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter year: ");
		int year = sc.nextInt();
		
		Calendar c = Calendar.getInstance();
		c.set(year, 2, 1);//Actually February 1st
		c.add(Calendar.DATE, -1);
		System.out.println("2月有 " + c.get(Calendar.DATE)+ "天");
	}

}

Notice:
        1. In java, the value of the field is not obtained by calling the field by the class. If you need to get the value of the field, you can only use the static method get().
        2. Regarding month calculation in java, January corresponds to 0, so if you need to get the actual monthly points, you need to give the field MONTH value +1.

System class
    

    The System class is an abstract class that has some useful class fields and methods and cannot be instantiated.
    Among the facilities provided by the System class are the standard input, standard output, and error output streams; access to externally defined properties and environment variables; methods for loading files and libraries; and utility methods for quickly copying part of an array.
Field summary
static PrintStream err
          The "standard" error output stream.
static InputStream in
          The "standard" input stream.
static PrintStream out
          The "standard" output stream.
It can be known that the in field is often used when we enter the keyboard, and the out field is often used when we print.


Common method:

public static void gc() Run the garbage collector
public static void exit(int status) Terminate the currently running Java virtual machine. The parameter is used as the status code; in general, the JVM needs to be terminated
    , then the parameter is 0
public static long currentTimeMillis() Returns the current time in milliseconds
public static void arraycopy(Object src,int srcPos, Object dest,int destPos, int length)  Copy an array from the specified source array, starting from the specified position and ending at the specified position in the target array
 src: original array
 dest: target array
 srcPos: where to start in the original array
 destPos: where to end in the target array
 length :length
Example: ( currentTimeMillis() and gc() )


   
   
   
 
 
public class Test1 {public static void main(String[] args) {//返回以毫秒为单位的当前时间,返回值为long型long ct = System.currentTimeMillis();System.out.println("time: "+ct +" ms");//这样用的意义不大
public class Test1 {public static void main(String[] args) {//返回以毫秒为单位的当前时间,返回值为long型long ct = System.currentTimeMillis();System.out.println("time: "+ct +" ms");//这样用的意义不大
                //可以用来计算运行一段代码的耗时,只需将代码放在两个时刻中间,然后计算两个时刻之间的时间即可求出。//gc()方法:用来回收不用的对象//先创建一个对象Person p = new Person("aloha", 22);System.out.println("回收前: "+p);//回收前: Person [name=aloha, age=22],因为p这个对象并不是无用对象。System.out.println("---------------------");//将p1空掉(不指定堆内存)Person p1 = new Person("alohaq", 221);p1 = null ;System.gc();System.out.println(p1);System.out.println(p);}}//这里写一个实体类:person 符合javabean规范的类就叫做实体类,类中变量、方法与sql存在对应关系。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;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}@Overrideprotected void finalize() throws Throwable {//重写垃圾回收器看看时候时候调用了这个方法System.out.println("不用这个对象了"+ this);super.finalize();}//有成员,有构造方法,有setget方法,有重写toString方法}

                //可以用来计算运行一段代码的耗时,只需将代码放在两个时刻中间,然后计算两个时刻之间的时间即可求出。//gc()方法:用来回收不用的对象//先创建一个对象Person p = new Person("aloha", 22);System.out.println("回收前: "+p);//回收前: Person [name=aloha, age=22],因为p这个对象并不是无用对象。System.out.println("---------------------");//将p1空掉(不指定堆内存)Person p1 = new Person("alohaq", 221);p1 = null ;System.gc();System.out.println(p1);System.out.println(p);}}//这里写一个实体类:person 符合javabean规范的类就叫做实体类,类中变量、方法与sql存在对应关系。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;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}@Overrideprotected void finalize() throws Throwable {//重写垃圾回收器看看时候时候调用了这个方法System.out.println("不用这个对象了"+ this);super.finalize();}//有成员,有构造方法,有setget方法,有重写toString方法}

打印结果:

    可以看到:System类中的currentTimeMillis()方法得到的值确实是以ms为单位的当前时间与1970年1月1日的差。对于gc()方法,它只会回收无用的对象,比如上例中我们创建了p,p1两个对象,我们把p1对象指向null,即不给它分配堆内存,那么p1对象就是我们垃圾回收器的回收对象。如何观察gc()方法调用了垃圾回收器finalize()方法?我们覆写了finalize()这个方法,在其中打印了一句话,就可以看到什么时候调用了垃圾回收器。
        exit(int status):可以结束死循环。status为0表示正常终止,不为0表示异常终止。

该方法调用 Runtime 类中的 exit 方法。该方法永远不会正常返回。 这个方法和finally有关系。

调用 System.exit(n) 实际上等效于调用:

 Runtime.getRuntime().exit(n)
       
         public static void arraycopy(Object src,int srcPos, Object dest,int destPos, int length):将src对象的srcPos开始的length长度的组复制覆盖到dest对象的destPos开始的组中。
例子:
import java.util.Arrays;

public class Test2 {
	
	public static void main(String[] args) {
		
		//System类中的数组复制方法
		int[] arr1 = {22,31,34,12,41,11};
		int[] arr2 = {11,23,42,543,63,22,234};
		System.out.println(Arrays.toString(arr1));
		System.out.println(Arrays.toString(arr2));
		
		System.arraycopy(arr1, 2, arr2, 2, 2);
		System.out.println(Arrays.toString(arr1));
		System.out.println(Arrays.toString(arr2));
	}
		
}
result
 

Date class

    Although the Date class has many methods that are outdated, there are methods in the Date class that we can use to implement time formatting and parsing. Conversion between String and Date types can be achieved. In addition, we create a Date object, then outputting this object will find that this object is the current time, accurate to milliseconds.
Example of d object:
import java.util.Date;

public class Test3 {
	public static void main(String[] args) {
		Date d = new Date();
		System.out.println(d);
	}
}

        DateFormat is an abstract class for date/time formatting that formats and parses datetimes in a language-independent manner. We can use the class SimpleDateFormat, a direct subclass of the DateFormat class, to implement the conversion between the Date and String classes, and there is a description of the date and time format in the SimpleDateFormat class.
Dates are formatted as Date->String. Parsing is the opposite. example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test3 {
	public static void main(String[] args) throws ParseException {
		Date d = new Date();
		System.out.println(d);
		//Create a Date object
		Date d1 = new Date();
		/**
		 * format
		 */
		//create sdf object
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		//格式化
		String str = sdf.format(d1);
		System.out.println(str);
		/**
		 * 解析
		 */
		String strt  = "2018-05-03" ;
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		Date d2 = sdf1.parse(strt);
		System.out.println(d2);
		
	}
}

练习例子:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 *键盘录入你的出生年月日,算一下你来到这个世界多少天? 
 *
 *分析:
 *		1)创建键盘录入对象,录入一个数据出生年月日
 *		2)1990-xx-xx
 *		3)将文本格式的数据解析成日期对象
 *		4)getTime() ; 获取出生所在日期的时间毫秒值
 *		5)获取当前系统时间毫秒值
 *		(6) 5)-4) =  long time
 *
 *		6)换算
 *		
 *
 */
public class Test4 {
	
	public static void main(String[] args) throws ParseException {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("按这个格式输入生日:yyyyMMdd");
		String birth = sc.nextLine();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Date bi = sdf.parse(birth);
		long t = bi.getTime();
		
		Date d = new Date();
		long nt = d.getTime();

		long t1 = (nt - t) /1000 /60 /60 /24;
		System.out.println("你来到这个世界:"+t1+"天");
	}
}

Math类

常用方法:
  public static int abs(int a):绝对值
  public static double ceil(double a):向上取整
  public static double floor(double a):向下取整
  public static int max(int a,int b):求最大值
  public static int min(int a,int b):求最小值
  public static double pow(double a,double b):a的b次幂
  public static double random()返回带正号的 double 值,该值大于等于 0.0 且小于 1.0
  public static int round(float a):四舍五入
  public static double sqrt(double a):一个数的正平方根

Random类

Random:是一个可以获取随机数的类

 public Random():无参构造方法
 public Random(long seed) :指定long类型的数据进行构造随机数类对象
 
 public int nextInt():获取随机数,它的范围是在int类型范围之内
 
 public int nextInt(int n):获取随机数,它的范围是在[0,n)之间

Guess you like

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