Home  >  Article  >  Java  >  Commonly used Java APIs: Object class, date and time class, StringBuilder class, packaging class

Commonly used Java APIs: Object class, date and time class, StringBuilder class, packaging class

php是最好的语言
php是最好的语言Original
2018-08-02 11:44:461845browse

This article introduces several commonly used Java APIs, such as Object class, date and time class, StringBuilder class, and packaging class, which will be frequently used in future development.

Object class

The Java.lang.Object class is the root class in the Java language, which is the parent class of all classes. All methods described by it can be used by subclasses. When an object is instantiated, the final parent class it looks for is Object.

The Object class contains 11 member methods. I only list two commonly used methods:

- public String toString():返回该对象的字符串表示。
- public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。

1.toString method

public String toString(): Returns the string representation of the object.

The toString method returns the string representation of the object. In fact, the content of the string is the type of the object@memory address value. Since the result returned by the toString method is the memory address, in development, it is often necessary to follow the object's The attribute gets its corresponding string representation, which is generally overridden.

Method override:

    //重写toString方法
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

2.equals method

public boolean equals(Object obj): Indicates whether some other object is related to this object "equal".

Call the member method equals and specify the parameter as another object, you can determine whether the two objects are the same. There are two ways of "same" here: default and custom.

If the equals method is not overridden, then the object address comparison of the == operator is performed by default in the Object class. As long as they are not the same object, the result must be false.

Method rewriting:

/*
        Object类的equals方法,默认比较的是两个对象的地址值
        重写equals方法,比较两个对象的属性
        问题:
            隐含这一个多态,无法使用子类特有的内容(属性和方法)
        解决:
            可以使用向下转型(强制类型转换)把o类型转换为Person
     */
    //重写equals方法
    @Override
    public boolean equals(Object o){
        //增加一个判断,如果传递的参数是this本身,直接返回true
        if(this==o) return true;

        //增加一个判断,如果传递的参数是null,直接返回false
        if(o==null) return  false;

        //增加一个判断,防止类型转换一次ClassCastException
        if(o instanceof Person){
            //使用向下转型,把o转换为Person类型
            Person p=(Person)o;
            //比较两个对象的属性,一个对象是this(p1),一个对象是p(o->p2)
            boolean b=this.name.equals(p.name) && this.age==p.age;
            return  b;
        }

        //不是Person类型,返回false
        return false;

Date and time class

1.Date class

java.util.Date class represents a specific instant, accurate to milliseconds .

Commonly used methods:

public long getTime() 把日期对象转换成对应的时间毫秒值。

Instance:

    /*
        long getTime() 把日期转换为毫秒值(相当于System.currentTimeMillis()方法)
        返回自1970年1月1日0点0分0秒 GMT以来此Date对象表示的毫秒数
     */
    public static void demo3(){
        Date date =new Date();
        long time=date.getTime();
        System.out.println(time);
    }

    //结果值
    1533119389083

2.DateFormat class

java.text.DateFormat is date/time An abstract class of the formatting subclass. We use this class to help us complete the conversion between dates and text, that is, we can convert back and forth between Date objects and String objects.

Formatting: Convert from Date object to String object according to the specified format.

Analysis: Convert from String object to Date object according to the specified format.

Two commonly used methods:

- public String format(Date date):将Date对象格式化为字符串。
- public Date parse(String source):将字符串解析为Date对象。

Example:

package demo2_Date;

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

public class Test02_Dateformat {
    public static void main(String[] args) throws ParseException {
        //将date对象格式化为字符串
        find_Date01();
        
        //将字符串解析为date对象
        find_Date02();
    }


    //将字符串解析为date对象
    public static void  find_Date01() throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String str="2018年8月1日 7点12分23秒";
        Date s=sdf.parse(str);
        System.out.println(new Date());
    }

    //将date对象格式化为字符串
    public static void  find_Date02(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        String s=sdf.format(new Date());
        System.out.println(s);
    }
}

Calculate the number of days of birth:

package demo2_Date;

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

/*
    计算出生天数
        1.键盘录入出生日期,并转换date类型(毫秒值)
        2.获取当前日期毫秒值
        3.相减得到差值毫秒值,转换得到天数
 */
public class Test03_FindBirthday {
    public static void main(String[] args) throws ParseException {
        //录入出生日期
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入你的出生日期:格式(yyyy-MM-dd)");
        String bithDateString=sc.next();

        //使用DateFormat类中的parse方法,把字符串类型的出生日期,转换成为date类型
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate=sdf.parse(bithDateString);

        //把出生日期转换为毫秒值
        long birthDateTime=birthDate.getTime();
        long nowDateTime=new Date().getTime();

        long daysTime=nowDateTime-birthDateTime;
        //获取天数
        System.out.println(daysTime/1000/60/60/24);
    }
}

Output result:

请输入你的出生日期:格式(yyyy-MM-dd)
1996-05-24
8104

Process finished with exit code 0

3. Calendar class

Concept:

java.util.Calendar is a calendar class that appears after Date and replaces many Date methods. This class encapsulates all possible time information as static member variables for easy access. The calendar class is convenient for obtaining various time attributes.

Acquisition method:

Calendar is an abstract class, which creates and returns subclass objects through static methods:

public static Calendar getInstance():使用默认时区和语言环境获得一个日历

Common methods: There are four common methods of Calendar, mainly mastering get Method and getTime method

- public int get(int field):返回给定日历字段的值。
- public void set(int field, int value):将给定的日历字段设置为给定值。
- public abstract void add(int field, int amount):根据日历的规则,为给定的日历字段添加或减去指定的时间量。
- public Date getTime():返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象

Instance:

package demo2_Date;
import java.util.Calendar;
import java.util.Date;

/*
    四种常用成员方法:
    - public int get(int field):返回给定日历字段的值。
    - public void set(int field, int value):将给定的日历字段设置为给定值。
    - public abstract void add(int field, int amount):根据日历的规则,
        为给定的日历字段添加或减去指定的时间量。
    - public Date getTime():返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象。
 */
public class Test04_Calendar {
    public static void main(String[] args) {
//        demo1();
//        demo2();
        demo3();
        demo4();
    }

    /*
    - public Date getTime():返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象。
     */
    public static void demo4(){
        Calendar cal=Calendar.getInstance();
        Date date=cal.getTime();
        System.out.println(date);   //Wed Aug 01 19:20:51 CST 2018
    }


    /*
     public abstract void add(int field, int amount):根据日历的规则,
        为给定的日历字段添加或减去指定的时间量。
     参数:设定指定的日历字段以及修改量
     返回值:修改过后的日历字段代表的值
     */
    public static void demo3(){
        Calendar cal =Calendar.getInstance();

        //加两年,减两月
        cal.add(Calendar.YEAR,+2);
        cal.add(Calendar.MONTH,-2);

        int year =cal.get(Calendar.YEAR);
        int month=cal.get(Calendar.MONTH)+1;
        int day=cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(year+"年"+month+"月"+day+"日");//   2020年6月1日
    }

    /*
     public void set(int field, int value):将给定的日历字段设置为给定值。
     参数:设定指定的日历字段以及设置值
     返回值:重新设定的日历字段代表的值
     */
    public static void demo2(){
        //创建Calendar对象
        Calendar cal= Calendar.getInstance();
        cal.set(Calendar.YEAR ,2020);
        int year=cal.get(Calendar.YEAR);
        System.out.println(year+"年");       //2020年
    }

    /*
        public int get(int field):返回给定日历字段的值。
        参数:传递指定的日历字段(YEAR,MONTH)
        返回值:日历字段代表的具体的值
     */
    public static void demo1(){
        //创建Calendar对象
        Calendar cal= Calendar.getInstance();
        //获取年份
        int year =cal.get(Calendar.YEAR);
        //获取月份
        int month=cal.get(Calendar.MONTH)+1;
        int day=cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(year+"年"+month+"月"+day+"日"); //2018年8月1日
    }
}

System class

1.currentTimeMillis method

Returns the current time in milliseconds, often used to test code Efficiency, such as looping code.

2.arraycopy method

Copies the data specified in the array to another array.

Example:

package demo3_System;

import java.util.Arrays;

/*
    两个常用方法:
        1.currentTimeMillis
        2.arraycopy
 */
public class Test01_System {
    public static void main(String[] args) {
        demo1();
        demo2();
    }

    //将数组中指定的数据拷贝到另一个数组中。
    public static void demo2(){
        int[] arr1={1,2,3,4,5};
        int[] arr2={6,7,8,9,10};
        System.arraycopy(arr1,0,arr2,0,3);
        System.out.println(Arrays.toString(arr2));      //[1, 2, 3, 9, 10]
    }

    //返回以毫秒为单位的时间
    public static void demo1(){
        long begin=System.currentTimeMillis();
        int sum=0;
        for(int i=0;i<10000;i++){
            System.out.println(i);
        }
        long end=System.currentTimeMillis();
        System.out.println(end-begin);  //205毫秒
    }

StringBuilder class

1. Overview

StringBuilder is also called a variable character sequence, it is a string similar to String Buffer, the length and content of the sequence can be changed through certain method calls. It turns out that StringBuilder is a buffer of strings, that is, it is a container that can hold many strings. And can perform various operations on the strings in it. It has an internal array to store string content. When concatenating strings, new content is added directly to the array. StringBuilder will automatically maintain the expansion of the array. The principle is as shown in the figure below: (default 16 character space, exceeds automatic expansion)

2. Commonly used methods:

- public StringBuilder append(...):添加任意类型数据的字符串形式,并返回当前对象自身。
- public String toString():将当前StringBuilder对象转换为String对象。

3. Example:

package demo4_StringBufilder;

public class Test01_StringBuilder {
    public static void main(String[] args) {
//        demo1();
        demo2();
    }

    //通过toString方法,StringBuilder对象将会转换为不可变的String对象
    public static void  demo2(){
        //创建对象
        StringBuilder str=new StringBuilder("会发光").append("的小太阳");
        //调用方法
        String atr1=str.toString();
        System.out.println(atr1);   //会发光的小太阳
    }

    //StringBuilder类的append方法,返回值是一个StringBuilder对象
    public static void demo1(){
        //创建对象
        StringBuilder str=new StringBuilder();
        //返回的是一个StringBuilder对象
        StringBuilder str2= str.append("会发光的");
        str2.append("小太阳");
        System.out.println("str2: "+str2);      //str2: 会发光的小太阳

        //调用一个方法返回值是一个对象的时候,可以使用返回值对象继续调用方法
        //链式编程
        str2.append("会吸光").append("小月亮");
        System.out.println("str2==: "+str2);    //str2==: 会发光的小太阳会吸光小月亮
    }
}

Packaging class

1.Basic type and corresponding packaging class

##Basic typeCorresponding packaging class (Located under the java.lang package) byteByteshortShortintIntegerlongLong floatFloatdoubleDoublechartChartbooleanBoolean

2. Unboxing and unboxing

The process of conversion back and forth between basic types and corresponding packaging class objects is called "boxing" and "unboxing":

Boxing: Convert from basic type to corresponding packaging class object.

Unboxing: Convert from the wrapper class object to the corresponding basic type.

3. Automatic unboxing and automatic boxing

Since we often need to convert between basic types and wrapper classes, starting from Java 5 (JDK 1.5), basic types and wrapper classes The packing and unboxing actions can be completed automatically, but we do not need to do it. That's right, this is automatic packing and automatic boxing. Surprising or not.

Related articles:

Explanation of common date classes in Java

The use of date classes and calendar classes in Java

【java tutorial】Java StringBuffer and StringBuilder classes

Basic type--Packaging class

The above is the detailed content of Commonly used Java APIs: Object class, date and time class, StringBuilder class, packaging class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn