Java --- > 常用API

常用API

方法重载: 方法名相同,方法接收的参数不同
static: 修饰的类,可以直接使用类名进行调用

方法名 说明
public static abs(int a) 返回参数的绝对值
public static double ceil(double a) 返回大于或等于
public static double floor(double a) 返回小于或等于参数的最大double值,等于一个整数
public static int round(float a) 按照四舍五入返回最接近参数的int
public static int max(int a, int b) 返回两个int值中的较大值
public static int min(int a, int b) 返回两个int值中的较小值
public static double pow(double a, double b) 返回a的b次幂
public static double random() 返回值为random的正值,[0.0, 1.0)

Math

public class MathDemo {
    public static void main(String[] args) {
        // 返回参数的绝对值
        System.out.println(Math.abs(88));
        System.out.println(Math.abs(-88));
        System.out.println("--------");

        // 返回大于或等于参数的最小double值(double类型)
        System.out.println(Math.ceil(12.34));
        System.out.println(Math.ceil(12.01));
        System.out.println("--------");

        // 返回小于或等于参数的最大double值(double类型)
        System.out.println(Math.floor(12.34));
        System.out.println(Math.floor(12.01));
        System.out.println("--------");

        // 返回最接近参数的int值  - 四舍五入
        System.out.println(Math.round(12.34F));
        System.out.println(Math.round(12.56F));
        System.out.println("--------");

        // 返回两个int值中较大的int值
        System.out.println(Math.max(66, 88));
        System.out.println("--------");

        // 返回两个int值中较小的int值
        System.out.println(Math.min(66, 88));
        System.out.println("--------");

        // 返回a的b次幂
        System.out.println(Math.pow(2.0, 3.0));
        System.out.println("--------");

        // 返回一个随机的double正值 [0.0, 1.0)
        System.out.println(Math.random());
        System.out.println((int) (Math.random() * 100));
    }
}

System

  • public static void exit(int status): 终止当前运行的Java虚拟机。该参数作为状态代码,非零状态码表示异常终止
  • public static long currentTimeMillis(): 返回当前时间(以毫秒为单位, 与1970年1月1日UTC之间的毫秒差值).

System包含几个有用的类字段和方法,它不能被实例化

public class SystemDemo {
    public static void main(String[] args) {
        System.out.println("开始");
        // public static void exit(int status): 终止当前运行的Java虚拟机,非零表示异常终止
//        System.exit(0);
        System.out.println("结束");

        // public static long currentTimeMillis(): 返回当前时间(以毫秒为单位)
        System.out.println(System.currentTimeMillis());

        // 计算当前时间与 UTC标准时间间隔多少天
        System.out.println(System.currentTimeMillis() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");

        long start = System.currentTimeMillis();
        // 计算for循环的时间
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("循环10000次,耗时" + (end - start) + "毫秒");
    }
}

Object

类Object是类层次结构的根。每个类都有Object作为超类。所有对象(包括数组)都实现了这个类的方法

构造方法: public Object()

回想面向对象中,为什么说子类的构造方法默认访问的是父类的无参构造方法?

因为它们的顶级父类,只有无参构造方法

看方法源码: 选中方法,按下 ctrl + b


toString方法

有学生类如下:

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

测试类: 创建一个学生类并输入

public class StudentDemo{
    public static void main(String[] args){
        Student s = new Student();
        s.setName("Marron");
        s.setAge(18);
        System.out.println(s);	// com.marron_01.Student@2d98a335
    }
}

以上结果为什么会是: com.marron_01.Student@2d98a335呢?

选中println方法,按下ctrl + b,同理.一层一层的往底层找去.得到如下的函数

public void println(Object x){
    String s = String.valueOf(x);
    synchronized(this){
        this.print(s);
        this.newLine();
    }
}

public static String valueOf(Object obj){
    return obj == null ? "null" : obj.toString();
}

public String toString() {
    return this.getClass().getName() + "@" + Integer.toHexString(this.hashCod());
}

当执行System.out.println(s)的时候,根据println的定义,此时 Object x中的x值为s

之后执行 String s = String.valueOf(x), 将x传入 public static String valueOf(Object obj)

此时的obj为x(非空),因此会返回一个obj.toString(). 此时的obj,实际上就是s。而Student类并没有toString方法.

这就涉及到一个隐式继承.即所有的类最终都会继承Object.而Object类中含有toString方法.故上述的Student类声明,实际上等同于下面:

public class Student extends Object{
    
}

可以通过以下方式验证:

public class StudentDemo{
    public static void main(String[] args){
        Student s = new Student();
        System.out.println(s);	// com.marron_01.Student@2d98a335
        System.out.println(s.toString());	// com.marron_01.Student@2d98a335
    }
}

【小结】:

public String toString(): 返回对象的字符串表示形式。一般来说,toString方法返回一个"toString"代表这个对象的字符串。结果应该是一个简明扼要的表达,容易让人阅读。建议所有子类重写此方法。

重写如下:

// Student.java
public class Student{
    // 其他方法略
    @Override
    public String toString() {
        return "Student{" + 
            	"name=" + "name" + "\" +
            	", age=" + age + 
            	"}";
    }
}

equals

需求: 还是上面的学生类,创建2个学生实例.让两个学生实例的内容相同.

public class ObjectDemo{
    public static void main(String[] args){
        Student s1 = new Student();
        s1.setName("Marron");
        s1.setAge(18);
        
        Student s2 = new Student();
        s2.setName("Marron");
        s2.setAge(18);
    }
}

判断两个学生实例的内容是否相同:

使用Object自带的equals进行比较

public boolean equals(Object obj){
    return this == obj;
}

tips: 调用时: s1.equals(s2); 此时比较的是s1和s2的地址值. 故需要重写equals方法

public class Student{
    private String name;
    private int age;
    
    @Override
    public boolean equals(Object o){
        if(this == o) return true;
        if( o == null || getClass() != o.getClass()) return false;
        
        Student student =(Student) o;
        if(age != student.age) return false;
        return name != null? name.equals(student.name) : student.name == null;
    }
}

Arrays


冒泡排序

冒泡排序: 一种排序的方式,对要进行排序的数据中相邻的数据进行两两比较,将较大的数据放在后面,依次对所有的数据进行操作,直至所有数据按要求完成排序.

  • 如果有n个数据进行排序,总共需要比较n-1此
  • 每一次比较完毕,下一次的比较就会少一个数据参与
public class ArrayDemo{
    public static void main(String[] args){
        int[] arr = {24, 69, 80, 57, 13};
        System.out.println("排序前: " + array2String(arr));
        
        // 排序
        int MAX_LEN = arr.length - 1;
        for(int x =0; x< MAX_LEN; x++){
            for(int i = 0; i< MAx_len - X; i++){
                if(arr[i] > arr[i+1]){
                    int tmp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = tmp;
                }
            }
        }
        System.out.println("排序后: " + array2String(arr));
    }
    public static String array2String(int[] arr){
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i =0; i< arr.length; i++){
            if(i == arr.length -1){
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}

使用Array包提供的方法进行排序

Arrays类包含用于操作数组的各种方法

方法名 说明
public static String toString(int[] a) 返回指定数组的内容的字符串表示形式
public static void sort(int[] a) 按照数字顺序排列指定的数组

工具类的设计思想:

  • 构造方法用private修饰
  • 成员用public static 修饰

这样的设计,强制程序员使用 类名.方法名()的方式…


基本类型包装类

将基本数据类型封装成对象的好处在于: 可以在对象中定义更多的功能方法操作该数据

常用的操作之一: 用于基本数据类型于字符串之间的转换

基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Integer类的概述和使用

Integer: 包装一个对象中的原始类型int的值

方法名 说明
public Integer(int value) 根据int值创建Integer对象(过时)
public Integer(String s) 根据String值创建Integer对象(过时)
public static Integer valueOf(int i) 返回表示指定的int值的Integer实例
public static Integer valueOf(String s) 返回一个保存指定值的Integer对象String
public class IntegerDemo{
    public static void main(String[] args){
        Integer i1 = Integer.valueOf(100);
        Integer i2 = Integer.valueOf("100");
        System.out.println(i1);
        System.out.println(i2);
    }
}

int和String的互相转换

基本类型包装类的最常见操作就是: 用于基本类型和字符串之间的相互转换

  1. int转换为String

public static String valueOf(int i): 返回int参数的字符串表示形式。该方法时String类中的方法

public class IntegerDemo{
    public static void main(String[] args){
        int num = 100;
        String s2 = String.valueOf(num);
    }
}
  1. String类型转换为int

public static int parseInt(String s): 将字符串解析为int类型。该方法是Integer类中的方法

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

栗子 - 字符串中数据排序

需求: 有一个字符串: “91 27 46 38 50”,请写程序实现最终输出结果是: “27 38 46 50 91”

思路是:

  1. 首先使用String[]接收split方法按空格划分的字符数组
  2. 将String[]类型转换成int[]类
  3. 使用Arrays.sort方法对int[] 进行排序
  4. 使用StringBuilder将int[]转换成StringBuilder类
  5. 将StringBuilder类转换成字符串得到最终结果
import java.util.Arrays;
public class IntegerTest{
    public static void main(String[] args){
        String s = "91 27 46 38 50";
        String[] strArr = s.split(" ");
        int[] arr = new int[strArr.length];
        for(int i = 0 ; i< arr.length; i++){
            arr[i] = Integer.parseInt(strArr[i]);
        }
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for(int i =0; i< arr.length; i++){
            if(i == arr.length -1){
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(" ");
            }
        }
        String res = sb.toString();
        System.out.println(res);
    }
}

自动装箱和拆箱

  • 装箱: 把基本数据类型转换为对应的包装类类型
  • 拆箱: 把包装类类型转换为对应的基本数据类型
// 自动装箱
Integer i = 100;	// JDK底层自动调用,等价于: Integer i = Integer.valueOf(100);

// 自动拆箱
i += 200;	// JDK底层自动调用,等价于: i = i.intValue() + 200. 然后自动装箱

注意: 在使用包装类类型的时候,如果做操作,最后先判断是否为null


日期类


Date类

方法名 说明
public Date() 分配一个Date对象,并初始化,以便它代表它被分配的时间,精确到毫米
public Date(long date) 分配一个Date对象,并将其初始化为表示标准基准时间起指定的毫秒数
public class DateDemo01{
    public static void main(String[] args){
        Date d1 = new Date();
    }
}

Date类的常用方法

方法名 说明
public long getTime() 获取的是日期对象从1970年1月1日00:00:00到现在的毫秒值
public void setTime(long time) 设置时间,给的是毫秒值
public class DateDemo02{
    public static void main(String[] args){
        // 创建日期对象
        Date d = new Date();
        
        // public long getTime();
        System.out.println(d.getTime() * 1.0 / 1000/60/60/24/365 + "年");
        
        long time = System.currentTimeMillis();
        d.setTime(time);
        System.out.println(d);
    }
}

SimpleDateFormat类概述

SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期。我们重点学习日期格式化和解析

日期和时间格式由日期和时间模式字符串指定,在日期和时间模式字符串中,从’A’到’Z’以及从’a’到’z’引号的字母被解释为表示日期或时间字符串的组件的模式字母

字母 含义
y
M
d
H
m
s
  • 格式化(从Date到String): public final String format(Date date): 将日期格式化成日期/时间字符串
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo{
    public static void main(String[] args){
        Date d = new Date();	// 生成一个距离UTC的毫秒时间
        
        // 创建一个时间规范: 该规范的format方法,会将Date格式转换成想要的日期String格式
        SimpleDateFormate sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String s = sdf.format(d);
        System.out.println(s);	// 2020年04月03日 23:42:04
    }
}
  • 解析(从String到Date): public Date parse(String source): 从给定字符串的开始解析文本以生成日期
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo{
    public static void main(String[] args) throws ParseException{
        String s = "2048-08-08 11:11:11";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse(s);
        System.our.println(d);	// Wed Aug 08 11:11:11 CST 2040
    }
}

栗子 - 日期工具类

需求: 定义一个日期工具类(DateUtils), 包含两个方法: 把日期转换为指定格式的字符串;把字符串解析为指定格式的日期,然后定义一个测试类(DateDemo),测试日期工具类的方法

  • 包装构造方法私有
public class DateUtils{
    private DateUtils(){}
}  

以上包装了该类无法被实例化,只能通过类.方法名的格式调用暴露出来的公共接口,下面是整体实现:

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

public class DateUtils{
    private DateUtils(){}
    
    // 把日期转换成字符串
    public static String dateToString(Date d, String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return new String(sdf.format(d));
    }
    
    // 把字符串转换成日期
    public static Date stringToDate(String s, String format) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(s);
    }
}
// 测试类如下
import java.text.ParseException;
import java.util.Date;

public class DateDemo {
    public static void main(String[] args) throws ParseException {
        // 创建日期对象
        Date d = new Date();
        String s1 = DateUtils.dateToString(d, "yyyy年MM月dd日");
        System.out.println(s1);

        String s2 = "2020-08-08 11:11:11";
        Date dd = DateUtils.stringToDate(s2, "yyyy-MM-dd HH:mm:ss");
        System.out.println(dd);
    }
}

Calendar类

Calendar为某一时刻和一组日历字段之间的转换提供了一些方法,并为操作日历字段提供了一些方法

Calendar提供了一个类方法getInstance用于获取Calendar对象,其日历字段已使用当前日期和时间初始化:Calendar rightNow = Calendar.getInstance()

import java.util.Calendar;

public class CalendarDemo {
    public static void main(String[] args) {
        // 获取对象
        Calendar c = Calendar.getInstance();    // 多态的形式
        System.out.println(c);

        // public int get(int field);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");
    }
}

Calendar的常用方法

方法名 说明
public int get(int field) 返回给定日历字段的值
public abstract void add(int field, int amount) 根据日历的规则,将指定的时间量添加或减去给定的日历字段
public final void set(int year, int month, int date) 设置当前日历的年月日
import java.util.Calendar;

public class CalendarDemo{
    public static void main(String[] args){
        Calendar c = Calendar.getInstance();
        
        // 10年后的7天前
        c.add(Calendar.YEAR,10);
        c.add(Calendar.DATE, -7);
        int year = c.get(Calendar.YEAR);
        int month=  c.get(Calendar.MONTH) + 1;
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");
        
        // 设置时间为2048年11月11日
        c.set(2048,10,11);
    }
}

二月天

需求: 获取任意一年的二月有多少天

【思路】: 首先获取键盘输入的年份,然后设置当前日期为该年的3月1日,之后设置天数建议,最好使用c.get获取天数.

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

public class CalendarTest{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入年份");
        int year = sc.nextInt();
        Calendar c = Calendar.getInstance();
        c.set(year, 2, 1);
        c.add(Calendar.DATE, -1);
        int day = c.get(Calendar.DATE);
        System.out.println(year + "年的二月份有" + day + "天");
    }
}
发布了228 篇原创文章 · 获赞 41 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/105430098
今日推荐