Class (another day when I don't know what to take)

Keywords: Java Back-end OOP

Tip: the following is the main content of this article. The following cases can be used for reference

1, Date class (time date class)

1. General

Date represents a specific time, accurate to milliseconds

2. Construction method

Method nameexplain
public Date()Allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds
public Date(long date)Allocates a Date object and initializes it to represent the specified number of milliseconds from the standard base time

3. Common methods

Method nameexplain
public long getTime()Gets the millisecond value of the date object from 00:00:00, January 1, 1970 to the present
public void setTime(long time)Set the time and give the value of milliseconds

The code is as follows (example):

import java.util.Date;

public class IntegerDemo {
    public static void main(String[] args) {
        Date d = new Date();
//        System.out.println(d.getTime());
//        System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "year")// Because the obtained time value is in milliseconds, we need to convert it into
        long time = System.currentTimeMillis();//current time 
//        long time = 1000*60*60;
        d.setTime(time);
        System.out.println(d);
    }
}

There is a particularly practical method (currentTimeMillis()), as an example: the time (in milliseconds) required to verify that the for loop prints numbers 1-9999
The code is as follows (example):

public class MathLib {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i=1;i<=9999;i++){
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("Spent a total of"+(end-start));
    }
}

When we need to calculate the running time of the program.

2, SimpleDateFormat class (time date class)

1. General

Is a concrete class for formatting and parsing dates in a locale sensitive manner.

2. Analysis

y year, m month, d day, H hour, m minute, s second

3. Construction method

Method nameexplain
public SimpleDateFormat()Construct a SimpleDateFormat, using the default mode and date format
public SimpleDateFormat(String pattern)Construct a SimpleDateFormat using the given pattern and the default date format

4. Common methods

  • Format (from Date to String)
    • public final String format(Date date): formats the date into a date / time string
  • Parsing (from String to Date)
    • public Date parse(String source): parses text from the beginning of a given string to generate a date

5. Cases

Case requirements: define a date tool class (DateUtils), which contains two methods: convert the date to a string in the specified format; Parse the string into a date in the specified format, and then define a test class (DateDemo) to test the methods of the date tool class
The code is as follows (example):

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

/*
Tool class
 Construction method private
 Member method static
 */
public class DateUtils {
    private DateUtils(){}
    //Date to String
    public static String dateToString(Date date,String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String s = sdf.format(date);
        return s;
    }
    //String to Date
    public static Date stringToDate(String s,String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d = sdf.parse(s);//Here's an exception. After the exception
        return d;
    }
}
import java.text.ParseException;
import java.util.Date;
public class DateDemo {
    public static void main(String[] args) throws ParseException {
        Date d = new Date();
        //My time is output in the format of yyyy MM dd HH:mm:ss
        String s1 = DateUtils.dateToString(d,"yyyy year MM month dd day HH:mm:ss");
        System.out.println(s1);
        //Similarly
        String s2 = DateUtils.dateToString(d,"yyyy year MM month dd day");
        System.out.println(s2);
        String s3 = DateUtils.dateToString(d,"HH:mm:ss");
        System.out.println(s3);
        System.out.println("-----------");
        String s = "2021-08-09 12:12:12";
        Date dd = DateUtils.stringToDate(s,"yyyy-MM-dd HH:mm:ss");
        System.out.println(dd);
    }
}

The url used here is the data requested by the network.

3, Calendar Class

1. General

Calendar It provides some methods for the conversion between a specific moment and a set of calendar fields, and some methods for manipulating calendar fields
Calendar Provides a class method getInstance Used to get generally useful objects of this type. The method returns a Calendar Object.
Its calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.getInstance();

2. Common methods

Method nameexplain
public int get(int field)Returns the value of the given calendar field
public abstract void add(int field, int amount)Add or subtract the specified amount of time from the given calendar field according to the rules of the calendar
public final void set(int year,int month,int date)Set the month, year and day of the current calendar

3. February day case

Case requirements: how many days are there in February of any year

The code is as follows (example):

import java.util.Calendar;
import java.util.Scanner;

public class DateDemo {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the year:");
        int year = sc.nextInt();
        //Set year, month and day of calendar object
        Calendar c = Calendar.getInstance();
        c.set(year,2,1);
        //March 1 is pushed forward one day, which is the last day of February
        c.add(Calendar.DATE,-1);
        //Just get the output of this day
        int date = c.get(Calendar.DATE);
        System.out.println(year+"In February"+date+"day");
    }
}

4, Math class

1. General

Math contains methods for performing basic numeric operations

2. Method calling method in math

If there is no constructor in the Math class, but the internal methods are static, they can be called through the class name

3. Common methods

Method name method nameexplain
public static int abs(int a)Returns the absolute value of the parameter
public static double ceil(double a)Returns the minimum double value greater than or equal to the parameter, which is equal to an integer
public static double floor(double a)Returns the maximum double value less than or equal to the parameter, which is equal to an integer
public static int round(float a)Returns the int closest to the parameter by rounding
public static int max(int a,int b)Returns the larger of the two int values
public static int min(int a,int b)Returns the smaller of the two int values
public static double pow (double a,double b)Returns the value of a to the power of b
public static double random()The return value is a positive value of double, [0.0,1.0)

Examples of common methods.
The code is as follows (example):

public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-34));
        System.out.println(Math.abs(34));
        System.out.println("------------");
        System.out.println(Math.ceil(12.34));
        System.out.println(Math.ceil(12.56));
        System.out.println("------------");
        System.out.println(Math.floor(12.34));
        System.out.println(Math.floor(12.56));
        System.out.println("------------");
        System.out.println(Math.round(12.34F));
        System.out.println(Math.round(12.56F));
        System.out.println("------------");
        System.out.println(Math.max(66,88));
        System.out.println("------------");
        System.out.println(Math.min(3,9));
        System.out.println("------------");
        System.out.println(Math.pow(2.0,3.0));
        System.out.println("------------");
        //System.out.println(Math.random());
        System.out.println((int)(Math.random()*100)+1);//Take a value from 1 to 100
    }
}

5, Object class

1. General

Object is the root of the class hierarchy. Each class can take object as a superclass. All classes directly or indirectly inherit from this class. In other words, all classes will have a copy of the methods of this class.
Why do subclass constructors access the parameterless constructors of the parent class by default? Because their top-level parent class only has parameterless constructors

2.toString method

In this case, the output is something we can't understand. We want to output it easily. We need to use the toString method.

(1) How to override the toString method

Alt + Insert choice toString
 In the blank area of the class, right-click -> Generate -> choice toString

(2) Function of toString method

It is more convenient to display the attribute values in the object in a good format

(3) Above case

The code is as follows (example):

package day12;

public class A {
    private String name;
    private int age;

    public A() {
    }

    public A(String name, int age) {
        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 "A{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class text {
    public static void main(String[] args) {
        A a = new  A("hjt",23);
        System.out.println(a);
    }
}

Final results

3.equals method

(1) Function of quals method

It is used to compare objects and return true and false results. For example, s1.equals(s2); s1 and s2 are two objects

(2) Scenario of overriding the equals method

If you don't want to compare the address values of the object and want to compare them in combination with the object attributes, alt + insert, select equals() and hashCode(), IntelliJ Default, all the way next and finish

(3) How to override the equals method

In the blank area of the class, right-click - > generate - > select equals() and hashCode(), and the following is the same as above.

(4) Examples

The code is as follows (example):

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        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 boolean equals(Object o) {
        //this ----s1
        //o    ----s2
        //Compare whether the addresses are the same. If they are the same, directly true
        if (this == o) return true;
        //Determine whether the parameter is null
        //Getclass()! = o.getclass() this sentence is used to judge whether it comes from the same class
        if (o == null || getClass() != o.getClass()) return false;

        //Downward transformation
        Student student = (Student) o;//student=s2;
        //Compare the same age
        if (age != student.age) return false;//age s1's age; student.age s2's age
        //Compare whether the contents of names are the same
        return name != null ? name.equals(student.name) : student.name == null;
    }

}

public class ObjectDemo {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("hjt");
        s1.setAge(21);

        Student s2 = new Student();
        s2.setName("hjt");
        s2.setAge(21);
        //Requirements; compare whether the contents of the two objects are the same
        //System.out.println(s1==s2);
        System.out.println(s1.equals(s2));
        /*
        public boolean equals(Object obj) {
            //this ----s1
            //obj  ----s2
            return (this == obj);
        }
         */
    }
}

summary

It will be added later.

Posted by Andy-H on Thu, 28 Oct 2021 19:58:26 -0700