[Java] Object class, common API and wrapper class

Keywords: Programming Java JDK

1, Object class

1. Introduction to object class

*The Object class is the parent class of all classes. If a class does not specify an inherited class, it inherits the Object. Any class directly or indirectly inherits from Object

2. Method of object class

① toString()
    * Source code
        public String toString() {
            return getClass().getName() + '@' + Integer.toHexString(hashCode())
        }
    * If not rewritten toString() Object type + @ + Hash value of address
    * Rewrite toString()
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
② equals()
    * Source code
        public boolean equals(Object obj) {
            return (this == obj);
        }
    * If not rewritten equals() Then compare the address values of the two objects
    * Rewrite equals()
        @Override
        public boolean equals(Object o) {
            //Determine whether it is the same object
            if (this == o) 
                return true;
            //Judge whether it is empty or the same reference type
            if (o == null || getClass() != o.getClass()) 
                return false;
            //Downward transformation
            Student_equals that = (Student_equals) o;
            //Return comparison results of content
            return age == that.age && Objects.equals(name, that.name);
        }

3. Objects tool class

* Objects.equals()
    public static boolean equals(Object a, Object b) {  
        return (a == b) || (a != null && a.equals(b));  
    }
* Objects.equals()Null pointer tolerance

2, Common API

1. Date class

① temporal origin
    //Greenwich: 1970-01-01 00:00:00
    //Beijing: 1970-01-01 08:00:00
② Date class
    Date Most of the methods of the class are out of date jdk1.1 Later on Carendar Class substitution
③ Construction method
    * public Date()
        //Assign a Date object and initialize it to represent the time (in milliseconds) it was allocated.
    * public Date(long date)
        //Assign a Date object and initialize it to represent the number of milliseconds since the origin.
④ getTime()
    * Converts the date object to the corresponding time millisecond value.
⑤ Example
    import java.util.Date;

    public class DemoDate {
        public static void main(String[] args) {
            Date date1 = new Date(1000 * 60 * 2);       //Thu Jan 01 08:02:00 CST 1970
            Date date2 = new Date(0);                     //Thu Jan 01 08:00:00 CST 1970
 
            //Nonparametric structure. Represents the current time L
            Date date3 = new Date();        //Wed May 29 13:41:42 CST 2019
 
            //Convert Date object to MS value
            long m = date3.getTime();       //1559108502853
 
            System.out.println(date1);
            System.out.println(date2);
            System.out.println(date3);
        }
    }

4. DateFormat class

① DateFormat introduce
    * DateFormat It is an abstract class and cannot be directly new Object, need to use subclass
② SimpleDateFormat
    * format
        //Create a SimpleDateFormat object with the date format symbol of the given schema and default locale
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    * rule
        y ---> year
        M ---> month
        d ---> day
        H ---> Time
        m ---> branch
        s ---> second
    * Method
        format()
            //Format, convert from Date object to String object according to the specified format.
        parse()
            //Parse, convert from String object to Date object according to the specified format.
③ Example
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Scanner;

    public class DemoDateFormat {
        public static void main(String[] args) throws ParseException {
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter the date of birth (Format: xxxx-xx-xx xx:xx:xx)");
            String s = sc.nextLine();
            //Date object
            Date date = new Date();
            //Formatting objects
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //Format current date
            String format = sdf.format(date);
            System.out.println(format);
 
            //Resolve incoming date
            Date parse = sdf.parse(s);
            //Count birth milliseconds
            long l = date.getTime() - parse.getTime();
            //Output milliseconds
            System.out.println(l);
            //Output age
            System.out.println(l / 1000 / 60 / 60 / 24 / 30 / 12);
        }
    }

5. Calendar Class

① The Calendar class is an abstract class, which provides getinstance() to get the subclass object of the Calendar class.
② Common methods
    * get(int field)
        Returns the value of the given calendar field.
    * set(int field, int value)
        Set the given calendar field to the given value.
    * add(int field, int amount)
        Adds or subtracts the specified amount of time for a given calendar field, based on the rules of the calendar.
    * getTime()
        Returns a Date object that represents the Calendar time value (the millisecond offset from the epoch to the present).
③ Member constant
    YEAR
    MONTH (starting from 0, can be used + 1)
    Day of month
    HOUR (12 HOUR system)
    Hour of day
    MINUTE
    SECOND second
    Day of week day of week
 Examples
    import java.util.Calendar;

    public class DemoCalendar {
        public static void main(String[] args) {
            //Create calendar object
            Calendar c = Calendar.getInstance();
            //This is the time
            c.set(2019,5,20);
            //Western months are: 0 - 11, the first day of the week is Sunday
            c.add(Calendar.MONTH,1);
            //Get the current time month and print
            System.out.println(c.get(Calendar.MONTH));
        }
    }

6. System class

① currentTimeMillis()
    Gets the millisecond interpolation between the system time and the time origin.
② arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
    Copies the data specified in the array to another array.
	
    * parameters 
        src source array
        srcPos source array start position
        dest target array
        destPos destination array start position
        Length copy length

7. StringBuilder class

① It has an array inside to store string content. When string splicing, new content is added directly to the array.
   StringBuilder will automatically maintain the expansion of the array. (default 16 character space, exceeding auto expansion)
② Construction method
    * public StringBuilder()
        Construct an empty StringBuilder container.
    * public StringBuilder(String str)
        Construct a StringBuilder container and add strings in it.
③ Common methods
    * append(String str)
        Adds a string form of any type of data and returns the current object itself.
    * toString()
        Converts the current StringBuilder object to a String object.
Examples
    public class DemoStringBuilder {
       public static void main(String[] args) {
            //Creating StringBuilder objects with parametric constructs
            StringBuilder sb = new StringBuilder("China");
            //Append character after sb
            sb.append("©");
            sb.append(2019);

            //Convert StringBuilder to string
            String s = sb.toString();
 
            System.out.println(s);
 
        }
    }

3, Packaging

1. Packing and unpacking

* [Packing] basic value ---> Packaging object
    //Using constructor functions
    Integer i1 = new Integer(int i);
    //Using the valueOf method in the wrapper class
    Integer i2 = Integer.valueOf(int i);
* [Unpacking] packing object ---> Basic value
    int num = i.intValue();
* from JDK 1.5 At the beginning, the packing and unpacking operations of basic types and packing classes can be completed automatically.
    Integer i = 1;//Auto boxing is equivalent to Integer i = Integer.valueOf(1);
    int a = i + 2;//Automatic unpacking is equivalent to i.intValue() + 2;

The wrapper class corresponding to the basic data type is described in Java? 06

2. Conversion between basic types and strings

In addition to the Character class, all other wrapper classes have a parseXxx static method that converts string parameters to their corresponding base types

* [Byte] parseByte(String s)
    Converts a string parameter to the corresponding byte base type.
* [Short]parseShort(String s)
    Converts a string parameter to the corresponding short base type.
* [Integer]parseInt(String s)
    Converts a string parameter to the corresponding int primitive type.
* [Long]parseLong(String s)
    Converts a string parameter to the corresponding long base type.
* [Float]parseFloat(String s)
    Converts a string parameter to the corresponding float primitive type.
* [Double]parseDouble(String s)
    Converts a string parameter to the corresponding basic double type.
* [Boolean]parseBoolean(String s)
    Converts a string parameter to the corresponding boolean primitive type.

3. example

public class DemoParse {
    public static void main(String[] args) {
        int num = Integer.parseInt("100");
    }
}

Posted by moleculo on Wed, 12 Feb 2020 05:14:52 -0800