Java Common API (b)

Java Common API (b)

1. Object class

  • Object class java.lang.Object located next packet.
  • It is the class Object class hierarchy root class (parent class) .
  • Each class uses the Object class as a superclass (parent class).
  • All objects (including arrays) are implemented method of this class.

  • public String toString (): Returns a string representation of the object.
  • public boolean equals (Object obj): indicate whether some other object with this object is "equal."

Precautions:

  1. See a class overrides the toString method, direct printing of this object class can be.
  2. If you do not override the toString method, the object is printed address value .
  3. Random class does not override method toString
  4. Scanner, ArrayList <E>class overrides the toString method.
  5. Equals method of Object class is the default address value comparison of two objects, the equals method String class is the equals method of Object class overwritten , and compares the contents of the string.

Polymorphic drawback: not use the specific content down subclass (attributes and methods).
Solution: Use downcast.

  • Example:
// Person.java
public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // 覆盖重写Object类中的toString方法
    @Override
    public String toString() {
       return "Person{" + "name='" + name + "\'" + ", age=" + age + "}";
    }
    
    // 覆盖重写Object类的equals方法
    @Override
    public boolean equals(Object obj) {
        // 判断是否等于自身
       if (obj == this){
           return true;
       }
       // 判断是否为空
       if (obj == null){
           return false;
       }
       // 判断是否为自定义的Person类
       if (obj instanceof Person){
           // 向下转型
           Person person = (Person)obj;
           return person.age == this.age && person.name.equals(this.name);
       }
       // 不是Person类直接返回false
       return false;
    }
    /*
    // 使用 alt + ins 添加的
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        // getClass()是使用反射技术判断 o 是否是Person类型 等效于 o instanceof Person
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }
    */

    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;
    }
}

// Demo02Main.java

import java.util.ArrayList;

public class Demo02Main {
    public static void main(String[] args) {
        Person one = new Person("迪丽热巴", 20);
        Person two = new Person("迪丽热巴", 20);

        System.out.println(one); // 没有重写之前打印的是地址值
        one.toString(); // Person{name='迪丽热巴', age=20}
//        System.out.println(one.toString()); // 没有重写之前打印的也是地址值
        System.out.println(one.equals(two)); // true
        System.out.println(one == two); // false

    }
}
  • Objects on the introduction of class

    In JDK 7 adds a Objects tool class, it provides methods to manipulate objects, it has some static practical method of composition, these methods are null-save (null pointer safety) or null-tolernt (tolerance null pointer), hashcode for calculating a target, returns a string representation of the object, to compare two objects.

When comparing two objects, Object equals method of easily throw a null pointer exception, class equals method Objects to optimize this problem, prevent null pointer exception.

  • Objects class equals method
public static boolean equals(Object a, Object b){
    return (a == b) || (a != null) && a.equals(b);
}

2. Date class

Outline

  • java.util.Date: represents the date and time of the class.
  • Date class represents a specific moment, with millisecond precision. 1 second = 1000 ms
  • Ms action value: can be calculated date and time.
  • Time origin: January 1, 1970 00:00:00 (Greenwich)
  • 1 day = 24 × 60 × 60 = 86400 milliseconds second = 86400000

Note:
China belongs to the East eight districts, the time will increase eight hours
January 1, 1970 08:00:00

// 输出当前时间距离时间原点的毫秒数,这是一个long类型
// 1565579081183L
System.out.println(System.currentTimeMillis());

Constructors and member methods

Date class space configuration parameters

  • Date (): Gets the current system time and date.
import java.util.Date;

public class DemoDate {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date); // Mon Aug 12 11:18:35 CST 2019 
    }
    
}

Date parameterized class structure

  • Date (long date): pass milliseconds, the value of the milliseconds installed for the date date.
 Date dateOne = new Date(1565579081183L);
        // Mon Aug 12 11:04:41 CST 2019
        System.out.println(dateOne);
        
Date dateTwo = new Date(0L);
        // Thu Jan 01 08:00:00 CST 1970
        System.out.println(dateTwo);

Members of the methods of the Date class:

  • long getTime (): Returns the number of milliseconds since January 1, 1970 00:00:00 GMT represented by this Date object.
public static void method03(){
        Date date = new Date();
        // 1565580373625
        // 相当于System.currentTimeMillis()方法
        System.out.println(date.getTime()); 
    }

3. DateFormat class

Outline

  • java.text.DateFormat: date / time formatting subclasses of the abstract class
  • Action: formatting (date -> text), parsing (text -> date)

Member method:

  1. String format (Date date): according to the designated mode, the date Date, formatted as a string matching the patterns.
  2. Date parse (String source): in line with the pattern string, resolves to Date date.

DateFormat class is an abstract class, you can not directly create objects to use, you can use a subclass of class DateFormat, SimpleDateFormat is a subclass of DateFormat.

java.text.SimpleDateFormat extends DateFormat

SimpleDateFormat类

  • SimpleDateFormat (String pattern): with the specified mode and default locale date and time formats symbol construction SimpleDateFormat
  • Parameters: String pattern: passing the specified mode (case sensitive).
  • Common formatting rules:
Identification letters (case sensitive) meaning
Y year
M month
d day
H Time
m Minute
s second

Note: You can not change mode letters, symbols connected mode can be changed.

DateFormat class format using the steps of the method:

  1. Create a SimpleDateFormat object constructor transfer mode specified.
  2. SimpleDateFormat method call in the format, according to the method specified in the configuration mode, the mode Date date formatted to conform to the character string (text).

Considerations when using the parse method:

  1. the parse a Date public (String Source) throws ParseException
    the parse method declares an exception: ParseException
  2. If the pattern string and construction methods are not the same, the program will throw this exception.
  3. Calling a method throws an exception, it must handle the exception, or throws continue to throw this exception or try catch with their own.
  • Example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DemoSimpleDateFormat {
    public static void main(String[] args) throws ParseException {
        // 首先将当前 Date格式化为 String
        // pattern:yyyy-MM-dd HH-mm-ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 创建一个Date对象
        Date date = new Date();
        
        // 调用SimpleDateFormat类中的format方法
        String format = sdf.format(date);
        System.out.println(format); // 2019-08-12 12:24:57

        // 将String解析为Date类
        Date parse = sdf.parse(format);
        System.out.println(parse); // Mon Aug 12 12:24:14 CST 2019

    }
}

Exercise

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

/*
题目要求:
使用日期时间相关的API,计算一个人已经出生了多少天?

分析:
1.输入你的出生日期,使用Scanner类中的next方法获取
2.将出生日期装换为毫秒
3.获取当前时间并装换为毫秒
4.差值 = 当前时间 - 出生日期
5.打印结果: 差值 / 1000/60/60/24
 */
public class DemoSimpleDateFormatTest {
    public static void main(String[] args) throws ParseException {
        // 创建一个Scanner对象
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的出生日期,格式:yyyy-MM-dd.");

        // 接受输入的出生日期
        String birthdayStr = sc.next();

        // 转换为 Date类
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthdayDate = sdf.parse(birthdayStr);

        // 装换为毫秒
        long birthdayTime = birthdayDate.getTime();

        // 获取当前时间并装换为毫秒
        long currentTime = new Date().getTime();

        // 计算差值

        long difference = currentTime - birthdayTime;
        // 装换为天数
        long liveDay = difference/1000/60/60/24;
        // 打印结果
        System.out.println(liveDay);
    }
}

4. Calendar category

  • java.util.Calendar classes: Class Calendar
  • The Calendar class is an abstract class that provides a lot of inside static methods (YEAR, MONTH, DAY_OF_MONTH, HOUR, etc.) control the calendar field.
  • Calendar class can not directly create objects to use, which has a static method getInstance (), which returns a subclass object Calendar class.
  • public static Calendar getInstance (): Use the default time zone and locale to get a calendar.

Common method

  1. public int get (int field): Returns the value of a given calendar field.
    Parameters: passing the given calendar field (YEAR, MONTH)
    Return Value: calendar field represented by a specific value

  2. public void set (int field, int value): the calendar field will be set to a given value.
    int field: passing a given calendar field.
    int value: to set the value of the specified calendar field.

  3. public abstract void add (int field, int amount): According to the calendar rules, for a given calendar field to add / subtract specified amount of time.
    int field: transfer the specified calendar field.
    int amount: increase / decrease the value specified.

  4. public Date getTime (): The Calendar object class installed for the Date object.

5. System Class

java.lang.System class provides a number of static methods, or the system can acquire information related to the operating system level.

Common method

  1. public static long currentTimeMillis (): returns the current time in milliseconds.
  2. public static void arraycopy (Object src, int srcPos, Object dest, int destPos, int length): copy the data specified in the array to another array.

System.currentTimeMillis () to the running time of the test system

public class DemoSystem {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        int sum = 0;
        for (int i = 0; i < 9999; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("程序耗时:" + time); 
    }
}

6. StringBuilder class

  • java.lang.StringBuilder

The principle of the String class

  • Strings are constant: their values ​​can not be changed after creation.
  • The bottom layer is a character string to be modified final byte array can not be changed, is a constant.
    private final byte [] value;
  • When adding the string, there will be a plurality of memory strings, space and more inefficient.

  • For example: Results of the string "a" + "b" + "c" is a calculated total of five strings are: "a", "b", "c", "ab", "abc".

Principle StringBuilder class

  • String buffer StringBuilder also called, can enhance the operational efficiency of the string (as a character string length may vary), the bottom layer is a string, but not final modification, the length may be varied. byte [] value = new byte [ 16];
  • String "a" + "b" + "c", the string will be four, namely: "a", "b", "c", "abc".
  • StringBuilder is always an array in memory of them, small footprint and high efficiency.
  • If you exceed the capacity of StringBuilder automatically expansion.

StringBuilder Constructor

  • public StringBuilder (): Constructs an empty string generator, an initial capacity of 16 characters.
  • public StringBuilder (String str): a string generator configured, and initialize the contents of the specified string.

StringBuilder common method

  • public StringBuilder append (...): add any type of representation of the data string, and returns the current object itself.
  • public String toString (): the current StringBuilder object to a String object.

  • StringBuilder and String interchangeable
    • String -> StringBuilder: StringBuilder method of using the constructor.
    • StringBuilder -> String: toString method using a StringBuilder.

Precautions:

  1. append method returns itself, which is this
  2. Using the append method does not need to accept the return value

7. packaging

Outline

Elementary data type is easy to use, but there is no corresponding method of operation of these basic types of data, you can use a class, the basic types of data packaged , defined methods in the class, this class is called wrapper class , we can use the method of operation of the class to these basic types of data.

Boxing and unboxing (an int Example)

Basic types and between the wrapper class objects, conversion back and forth process is called "packing" and "unpacking."

  • Packing: basic types installed for the corresponding wrapper class object.
  • Unpacking: from the packaging installed for the class object substantially corresponding to the type.

A, packing
boxes in two ways, one method of construction, another static method, the following constitution methods obsolete.

  1. Construction method:
  • public Integer (int value): Constructs a newly allocated Integer object that represents the specified int value.
  • public Integer (String s): Integer object to construct a new distribution which represents the int value indicated by the String parameter. The string corresponding to the basic types of transfer, otherwise it will throw an exception: a NumberFormatException , for example: "100" right, "A" error.
  1. Static methods:
  • public static Integer valueOf (int i): Returns a Integer instance representing the specified int value.
  • public static Integer valueOf (String s): Returns Integer String object values ​​stored specified.

Second, unpacking
member method:

  • int intValue (): returns an int value Intrger.

Automatic boxing and unboxing automatic

  • Automatic conversion between the basic data types and packaging.
  • From the beginning JDK 1.5+ supports automatic boxing and auto-unboxing.

Conversion between basic types and string types

A basic types -> String type

  1. Value of the basic type + "" The easiest way (commonly work).
  2. Packaging of static methods: toString toString (parameter), not class Object () is overloaded public static String toString (int i): Returns a String object representing the specified integer.
  3. String class static methods: valueOf (int i): int Returns a string representation of the argument.

Second, the string type -> basic types

  1. Static method parseXXX wrapper class ( "numeric string type");
    Integer class: public static the parseInt (S String)
    Double class: public static parseDouble (String s)
// 基本类型 --> 字符串类型
        int i1 = 100;
        String s1 = i1 + "";
        System.out.println(s1); // 100

        int i2 = 100;
        String s2 = Integer.toString(i2);
        System.out.println(s2 + 200); // 100200

        int i3 = 100;
        String s3 = String.valueOf(i3);
        System.out.println(s2 + 200); // 100200

        // 字符串类型 --> 基本类型
        String s4 = "100200";
        int i4 = Integer.parseInt(s4);
        System.out.println(i4); // 100200

Guess you like

Origin www.cnblogs.com/blog-S/p/11348171.html
Recommended