Java面向对象常用API学习

Java面向对象常用API

一、Math类

1.1 math类概述

math包含执行基本数字运算的方法

扩展:没有构造方法,如何使用类中的成员呢?

看类的成员是否都是静态,如果是,通过类名就可以直接调用。

1.2 math类的常用方法

方法名说明
public static abs(int a)返回参数的绝对值
public static double ceil(double a)返回大于或等于参数的最小double值,等于一个整数
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返回值为double的正值[0.0,1.0)
public class MathTest {
    public static void main(String[] args) {
        System.out.println(Math.abs(-88));
        System.out.println(Math.ceil(6.6));
        System.out.println(Math.floor(6.6));
        System.out.println(Math.round(6.6));
        System.out.println(Math.max(6,11));
        System.out.println(Math.min(6,11));
        System.out.println(Math.pow(2.0,3.0));
        System.out.println(Math.random());
    }
}

二、System类

2.1 System概述

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

2.2 System类的常用方法

方法名说明
public static void exit(int status)停止当前运行的Java虚拟机,非零表示异常终止
public static long currentTimeMillis()返回当前时间(以毫秒为单位)
public class SystemTest {
    public static void main(String[] args) {
        //只输出开始
        System.out.println("开始");
        System.exit(0);
        System.out.println("结束");
        System.out.println("--------------");
        //求1970年到现在多少年
        System.out.println(System.currentTimeMillis()*1.0/1000/60/60/24/365);
        //求执行循环时间
        long start =System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("共耗时"+(end-start)+"毫秒");
    }
}

三、Object类

3.1 Object类的概述

Object是类层次结构的跟,每个类都可以将Object作为超类。所有类都直接或间接的继承自该类。

构造方法:public Object()

  • 为什么说子类的构造方法默认访问的是父类的无参构造方法?
  • 因为它们的顶级父类只有无参构造方法

3.2 Object常用方法

方法名说明
public String toString()返回对象的字符串表示形式。建议所有子类重写该方法,自动生成。
public boolean equals(Object obj)比较对象是否相等。默认比较地址,重写可以比较内容,自动生成。
3.2.1 to String()方法
public String toString()

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

该toString类方法Object返回一个由其中的对象是一个实例,该符号字符的类的名称的字符串@ 和对象的哈希码的无符号的十六进制表示。 换句话说,这个方法返回一个等于下列值的字符串:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
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 ObjectDemo {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("xuanxuan");
        student.setAge(22);
        System.out.println(student);
        System.out.println(student.toString());
    }
}

数据结果:

object.Student@1b6d3586
object.Student@1b6d3586

之后在Student类中重写to String方法:

   @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

运行结果:

Student{name='xuanxuan', age=22}
Student{name='xuanxuan', age=22}
3.2.2 equals()方法

指示一些其他对象是否等于此。

equals方法在非空对象引用上实现等价关系:

  • 自反性 :对于任何非空的参考值x ,x.equals(x)应该返回true 。
  • 它是对称的 :对于任何非空引用值x和y ,x.equals(y)应该返回true当且仅当y.equals(x)回报true 。
  • 它是一致的 :对于任何非空引用值x和y ,多次调用x.equals(y)始终返回true或始终返回false ,没有设置中使用的信息equals比较上的对象被修改。
  • 对于任何非空的参考值x ,x.equals(null)应该返回false 。

该equals类方法Object实现对象上差别可能性最大的相等关系; 也就是说,对于任何非空的参考值x和y ,当且仅当x和y引用相同的对象( x == y具有值true )时,该方法返回true 。

请注意,无论何时覆盖该方法,通常需要覆盖hashCode方法,以便维护hashCode方法的通用合同,该方法规定相等的对象必须具有相等的哈希码。

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

    public Person() {
    }

    public Person(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 ObjectDemo {
    public static void main(String[] args) {
        Person person1 = new Person();
        person1.setName("xuanxuan");
        person1.setAge(22);
        Person person2 = new Person();
        person2.setName("xuanxuan");
        person2.setAge(22);
        System.out.println(person1 == person2);
    }
}

运行结果:false

之后在Person类中重写equals方法:

    @Override
    public boolean equals(Object o) {
        //比较地址是否相同,如果相同,直接返回true
        if (this == o) return true;
        //首先判断参数是否为null,再判断两个对象是否来自同一个类
        if (o == null || getClass() != o.getClass()) return false;
        //向下转型
        Person person = (Person) o;

        if (age != person.age) return false;
        return name != null ? name.equals(person.name) : person.name == null;
    }
public class ObjectDemo {
    public static void main(String[] args) {
        Person person1 = new Person();
        person1.setName("xuanxuan");
        person1.setAge(22);
        Person person2 = new Person();
        person2.setName("xuanxuan");
        person2.setAge(22);
        System.out.println(person1.equals(person2));
        /*    public boolean equals(Object obj) {
              //this --- person1
              //obj --- person2
              return (this == obj);
         }*/
    }
}

运行结果:true

四、Arrays类

4.1 冒泡排序

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

4.2 Arrays类的概述

  • 该类包含用于操作数组的各种方法(如排序和搜索)。 该类还包含一个静态工厂,可以将数组视为列表。

4.3 Arrays类的常用方法

public class ArraysDemo {
    public static void main(String[] args) {
        int[] arr = {24,69,80,57,13};
        System.out.println("排序前:" + Arrays.toString(arr));
        Arrays.sort(arr);
        System.out.println("排序后:" + Arrays.toString(arr));
    }
}

工具类的设计思想:

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

五、基本类型包装类

5.1 基本类型包装类概述

将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据常用的操作之一:用于基本数据类型与字符串之间的转换

基本数据类型包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

5.2 Integer类型包装类概述和使用

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

5.3 int和String的相互转换

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

5.3.1 int转换为String

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

5.3.2 String转换为int

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

public class IntegerString {
    public static void main(String[] args) {
        int number = 100;
        //Int 转 String
        //方法一
        String s1 = "" + number;
        System.out.println(s1);
        //方法二
        String s2 = String.valueOf(100);
        System.out.println(s2);

        //String 转 Int
        String number2 = "100";
        //方法一 String转Integer再转Int
        Integer i = Integer.valueOf(number2);
        //public int intValue()
        int num = i.intValue();
        System.out.println(num);
        //方法二 String直接转Int
        //public static int parseInt(String s)
        int num2 = Integer.parseInt(number2);
        System.out.println(num2);
    }
}

小练习:

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

    public static void main(String[] args) {
        String s = "91 27 46 38 50";
        //将字符串中的数字存储到一个int类型的数组中。
        //public String[] split(String regex)
        String[] strArray = s.split(" ");
        //定义一个int数组,把String[]数组中的每一个元素存储到int数组中
        //public static int parseInt(String s)
        int[] arr = new int[strArray.length];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = Integer.parseInt(strArray[i]);
        }
        //对int数组进行排序
        Arrays.sort(arr);
        //把排序后的int数组中的元素进行拼接得到一个字符串,这里拼接采用StringBuilder来实现。
       StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            if(i == arr.length -1){
                stringBuilder.append(arr[i]);
            }else{
                stringBuilder.append(arr[i]).append(" ");
            }
        }
        String s1 = stringBuilder.toString();
        System.out.println(s1);
    }
}

5.4 自动装箱和拆箱

  • 装箱:把基本数据类型转换为对应的包装类类型
  • 拆箱:把包装类类型转换为对应的基本数据类型
public class BaozhuangDemo {
    public static void main(String[] args) {
        //装箱:把基本数据类型转换为对应的包装类类型
        Integer i = Integer.valueOf(100);
        //自动装箱
        Integer i2 = 100;
        //拆箱:把包装类类型转换为对应的基本数据类型
        i2 = i2.intValue() + 200;
        //自动拆箱
        i2+=200;
        Integer i3 = null;
        if(i3!=null){
            i3 += 300;
        }
    }
}

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

六、日期类

6.1 Date类概述和构造方法

Date代表了一个特定的时间,精确到毫秒

方法名说明
public Date()分配一个Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒
public Date(long date)分配一个Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数
public class DateDemo {
    public static void main(String[] args) {
        //public Date()分配一个Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒
        Date date = new Date();
        System.out.println(date);   //Fri Mar 18 09:04:29 GMT+08:00 2022    现在时间
        //public Date(long date)分配一个Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数
        long dateNum = 1000*60*60;  //一个小时
        Date date2 = new Date(dateNum);
        System.out.println(date2);  //Thu Jan 01 09:00:00 GMT+08:00 1970    1970往后一个小时
    }
}

6.2 Date类常用方法

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

        //public void setTime(long time)设置时间,给的是毫秒值
        Date date2 = new Date();
        // long time2 = 1000 * 60 * 60;
        //获取系统当前时间
        long time2 = System.currentTimeMillis();
        date2.setTime(time2);
        System.out.println(date2);
    }
}

6.3 SimpleDateFormat类

6.3.1SimpleDateFormat类概述
  • SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期。 它允许格式化(日期文本),解析(文本日期)和归一化。
  • 日期和时间格式由日期和时间模式字符串指定。 在日期和时间模式字符串中,从’A’到’Z’和从’a’到’z’的非引号的字母被解释为表示日期或时间字符串的组件的模式字母。 可以使用单引号( ’ )引用文本,以避免解释。 "‘’"代表单引号。 所有其他字符不被解释; 在格式化过程中,它们只是复制到输出字符串中,或者在解析过程中与输入字符串匹配。

  • 常用的模式字母以及对应关系如下:
    在这里插入图片描述

6.3.2 SimpleDateFormat的构造方法
方法名说明
public SimpleDateFormat()构造一个SimpleDateFormat,使用默认模式和日期格式
public SimpleDateFormat(String pattern)构造一个SimpleDateFormat使用给定的模式和默认的日期格式
6.3.3 SimpleDateFormat格式化和解析
  • 格式化(从Date到String)
public final String format(Date date):将日期格式化成日期/时间字符串
  • 解析(从String到Date)
public Date parse(String source):从给定的字符串开始解析文本以生成日期
public class Demo3 {
    public static void main(String[] args) throws ParseException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        String format = simpleDateFormat.format(date);
        System.out.println(format);
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String format2 = simpleDateFormat2.format(date);
        System.out.println(format2);
        //String转Date
        String date2 = "2022-02-26 11:11:11";
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date3 = simpleDateFormat3.parse(date2);
        System.out.println(date3);
    }
}

6.4 日期工具类

/*
* 需求:定义一个日期工具类(DateUtils),包含两个方法:把日期转换为指定格式的字符串;把字符串解析为指定格式的日期,然后定义一个测试类(DateDemo),测试日期工具类的方法。
* */
public class DateUtils {
    private  DateUtils(){}
    //把日期转换为字符串
    public static String dateToString(Date date, String format){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        String s = simpleDateFormat.format(date);
        return s;
    }
    //把字符串转换为日期
    public static Date stringToDate(String s,String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = simpleDateFormat.parse(s);
        return date;
    }
}

6.5 Calendar类(日历类)

6.5.1 概述
  • Calendar为某一时刻和一组日历字段之间的转换提供了一些方法,并为操作日历字段提供了一些方法。
  • Calendar的getInstance方法返回一个Calendar对象,其日历字段已使用当前日期和时间进行初始化:

    Calendar rightNow = Calendar.getInstance();
    
    6.5.2 Calendar类(日历类)常用方法
方法名说明
public int get(int field)返回给定日历字段的值
public abstract void add(int field,int amount)根据日历的规则,将指定的时间添加或减去给定的日历字段
public final void set(int year,int moonth,int date)设置当前日历的年月日
public class CalendarDemo {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar);
        //public int get(int field)返回给定日历字段的值
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");
        //public abstract void add(int field,int amount)根据日历的规则,将指定的时间添加或减去给定的日历字段
        //十年前的五天前
        calendar.add(Calendar.YEAR, 10);
        calendar.add(Calendar.DATE, -5);
        int year2 = calendar.get(Calendar.YEAR);
        int month2 = calendar.get(Calendar.MONTH) + 1;
        int date2 = calendar.get(Calendar.DATE);
        System.out.println(year2 + "年" + month2 + "月" + date2 + "日");
        //public final void set(int year,int moonth,int date)设置当前日历的年月日
        calendar.set(2000,2,26);
        int year3 = calendar.get(Calendar.YEAR);
        int month3 = calendar.get(Calendar.MONTH) + 1;
        int date3 = calendar.get(Calendar.DATE);
        System.out.println(year3 + "年" + month3 + "月" + date3 + "日");
    }
}

小demo输入年份输出2月份有多少天?

public class CalendarDemo2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入日历年份:");
        int year = scanner.nextInt();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, 2, 1);
        calendar.add(Calendar.DATE, -1);
        int date = calendar.get(Calendar.DATE);
        System.out.println(year + "年的2月份有" + date + "天");
    }
}

“人生这条路很长,未来如星辰大海摧残,不必踌躇与过去的半亩方塘。那些所谓的遗憾可能是一种成长;那些曾受过的伤,终会化作照亮前路的光。”

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值