Java基础学习笔记(五) - 常用的API

API介绍

概念:API 即应用编程程序接口。Java API是JDK中提供给我们使用的类说明文档,这些类将底层的代码实现封装。无需关心这些类是如何实现,只需要学习如何使用。

使用:通过API找到需要使用的类,学习使用构造方法和成员方法。(创建对象,调用即可)

一、Scanner类

功能:解析基本类型和字符串的简单文本扫描器。

构造方法:无参构造 Scanner,生成的值是从指定输入流扫描的。

成员方法:

nextInt 方法会将输入信息记录为int类型。

import java.util.Scanner; //导包
public class TestScanner {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("正在录入数据:");
        int a = sc.nextInt();
        System.out.println(a);

    }
}

System.in 表示通过键盘录入数据,然后使用 Scanner类的 nextInt 方法获取输入数据。

使用导包:使用 import 关键字,引入包中的类。java.lang 包下的类无需导入。

二、Random类

功能:生成伪随机数。

构造方法:无参构造随机数生成器。

成员方法:

nextInt 方法会返回一个伪随机数,范围在0(包含)-n(参数,不包含)之间。

import java.util.Random;
public class TestRandom {
    public static void main(String[] args){
        Random R = new Random(); //创建随机数生成器
        System.out.println(R.nextInt(10)); 
    }
}

三、ArrayList类

功能:ArrayList 集合类会创建一个大小可变的数组,用于存储和操作对象数据。

构造方法:无参构造一个空集合。

成员方法:

  • add 方法将指定的元素添加到集合的尾部。(添加的数据必须和创建ArrayList对象时声明的数据类型一致)
  • remove 方法移除集合指定位置上的元素,并返回被删除的元素。
  • get 方法返回集合中指定位置上的元素,并返回获取的元素。
  • size 方法返回集合中的元素数量。用于遍历集合是,控制索引,防止指针越界。
import java.util.ArrayList;
public class TestArrayList {
    public static void main(String[] args){
        //创建对象并声明集合类型为Integer
        ArrayList<Integer> list = new ArrayList<>(); //jdk7后的版本右侧<>可不写内容
        //添加 int 类型元素
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        System.out.println(list);
        //获取指定位置的元素 注意指针越界
        System.out.println(list.get(0));
        //删除指定位置的元素 注意指针越界
        System.out.println(list.remove(1));
        //遍历打印
        printArrayList(list);
    }
    //遍历打印
    public  static  void printArrayList(ArrayList<Integer> list){
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }
}

 ArrayList 对象不能存储基本类型,只能存储引用类型的数据,但是可以存储基本数据类型对应的包装类型(见本文第十一节)。

 四、String类

功能:类 String 包括用于检查各个字符串的方法。

特点:

  1. 字符串的值创建后不能更改。
  2. 可以被共享。
  3. String底层使用字符数组实现的。“abc”等效于 “char[] data = {'a' ,'b' ,'c' }”。

构造方法:

  • 无参构造创建一个新的空字符 String对象。
  • char[] value :通过当前参数中的字符数组构造。
  • byte[] bytes:通过使用平台默认字符集解码当前参数中的字节数组构造。
public class TestString {
    public  static void  main(String[] args){
        //构造方法
        //无参构造
        String str1 = new String();
        //字符数组构造
        char chars[] = {'a','b','c'};
        String str2 = new String(chars);
        //字节数组构造
        byte bytes[] = {97,98,99};
        String str3 = new String(bytes);

     }

}

 成员方法:

方法 返回值类型 参数 功能
equals  boolean object 用于将此字符串与指定对象比较。相同为true,不同为false。
equalsIgnoreCase  boolean

str

equalsIgnoreCase 方法和 equals 方法相同,只不过在比较时会忽略大小写。

length  int   返回字符串的长度
concat String str 将指定的字符串连接到该字符串的末尾
charAt char index 返回指定索引处的char值
indexOf int str 返回指定字符串第一次出现在该字符串内的索引
substring   String beginIndex,endIndex

无endIndex从beginIndex到结尾截取字符串

有endIndex从beginIndex到endIndex(不含endIndex)

toCharArray char[]   将字符串转换为新的字符数组
getBytes byte[]   使用平台默认字符集将String转换为新的字节数组
replace String targe,replacement 将与target匹配的字符串替换为replacement
split String[] regex 将字符串按照regex拆分为字符串数组
package com.api;


public class TestString {
    public  static void  main(String[] args){
        //构造方法
        //无参构造
        String str1 = new String();
        //字符数组构造
        char chars[] = {'a','b','c'};
        String str2 = new String(chars);
        //字节数组构造
        byte bytes[] = {97,98,99};
        String str3 = new String(bytes);

        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);

        //字符串比较(区分大小写) 相同为true,否则为false
        System.out.println(str2.equals(str3));
        System.out.println(str1.equals(str3));

        //字符串比较(不区分大小写) 相同为true,否则为false
        String str4 = "ABC";
        System.out.println(str2.equalsIgnoreCase(str4));

        //获取长度
        System.out.println(str2.length());
        //字符串连接(指定字符串连接末尾)
        System.out.println(str2.concat(str4));
        //获取指定索引处的字符
        System.out.println(str2.charAt(0));
        //获取一个字符串在字符串对象中第一次出现的索引,没有则返回1
        System.out.println(str2.indexOf("b"));
        System.out.println(str2.indexOf("d"));
        //从start索引开始截取字符串,end存在截取不会包含end
        System.out.println(str2.substring(1));
        System.out.println(str2.substring(1,2));

        //转换字符数组
        System.out.println(str2.toCharArray());
        System.out.println(str2.getBytes());
        //替换字符
        System.out.println(str3.replace("a","R"));
        //拆分数组
        System.out.println(str3.split("b"));
    }

}

五、Math类

功能:包含用于执行基本数学运算的方法,如初等指数,对数,平方根和三角函数。

特点:调用简单,所有方法均为静态方法。(静态方法使用static修饰,无需创建类对象即可调用)

public class TestMath {
    public static void main(String[] args){
        //绝对值
        double d1 = Math.abs(-1);
        //向上取整
        double d2 = Math.ceil(1.1);
        //向下取整
        double d3 = Math.floor(1.1);
        //四舍五入
        double d4 = Math.round(2.4);
    }
}

六、Object类

概述:Object 类是Java语言中的根类,即所有类的父类。如果一个没有指定继承父类,都会默认继承 Object 类。

部分方法:

toString 方法:返回对象的字符串表示。

equals 方法:比较两个对象是否相同。

public class TestObject{
    public static void main(String[] args){
        String a = "abc";
        System.out.println(a.toString());
        String b = "abc";
        System.out.println(a.equals(b));
    }
}

 

 七、时间日期类

1.Date 类

功能:表示特定的时间,精确到毫秒。

构造方法:无参构造自动获取系统当前时刻。指定参数long date 可以自定义毫秒时刻。

成员方法:public long getTime()把日期对象转换成对应的时间毫秒值。

import java.util.Date;
public class TestDate {
    public static void main(String[] args){
        System.out.println(new Date());
        System.out.println(new Date(0L));
        System.out.println(new Date().getTime());
    }
}

 2.DateFormat 类(抽象类)

功能:完成Date对象和String的相互转换。

构造方法:使用 public SimpleDateFormat(String pattern) 子类。指定一个格式来格式化或解析的标准。

成员方法:

  • public String format(Date date) :将Date对象格式化为字符串对象。
  • public Date parse(String source):将字符串解析为Date对象。
 
 
import java.text.ParseException;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class TestDateFormat {
    public static void main(String[] args) throws Exception {
        //创建时间对象
        Date d = new Date();
        System.out.println(d);
        //创建日期格式化对象
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(df);
        //时间对象格式化为字符串
        String str1 = df.format(d);
        System.out.println(str1);
        //字符串解析为Date对象
        Date d2 = df.parse(str1);
        System.out.println(d2);

    }
}
Date d2 = df.parse(str1);总是异常,为方法添加 throws Exception,忽略异常。

八、Calendar类

功能:日历类,该类将所有可能用到的时间信息封装为静态成员变量,方便获取各个时间属性。

Canlendar为抽象类,创建对象是并非直接创建而是通过静态方法创建,返回子类对象。

静态方法:public static Calendar getInstance() 使用默认时区和语言环境获得一个日历。

成员方法:

  • public int get(int field):返回给定日历字段的值。
  • public void set(int field, int value):将给定的日历字段设置为给定值。

  • public abstract void add(int field, int amount):根据日历的规则,为给定的日历字段添加或减去指定的时间量。

  • public Date getTime():返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象。

 
 
import java.util.Calendar;
import java.util.Date;
public class TestCalendar {
    public static void main(String[] args){
        //创建Calendar对象
        Calendar cal = Calendar.getInstance();
        //get设置年月日
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        //set修改年月日
        cal.set(Calendar.YEAR,2020);
        cal.set(Calendar.MONTH,1);
        cal.set(Calendar.DAY_OF_MONTH,1);
        //add 在原值基础上加减
        cal.add(Calendar.DAY_OF_MONTH,1);//加1天
        //getTime 获取对应的Date对象
        Date date = cal.getTime();

    }
}

九、System类

功能:提供了大量的静态方法,可以获取与系统相关的信息或系统级操作。

成员方法:

1、public static long currentTimeMillis():返回当前系统时间与1970年01月01日00:00点之间的毫秒差值。

public class TestSystem {
    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }
}

 2、public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):将数组中指定的数据拷贝到另一个数组中。

public class TestSystem {
    public static void main(String[] args) {
        int[] arr1 = new int[]{1,2,3,4,5};
        int[] arr2 = new  int[]{6,7,8,9,10};
        //拷贝指定位置数据覆盖指定位置0-3
        System.arraycopy( arr1, 0, arr2, 0, 3);
    }
}

十、StringBuilder类

前面提到 String 对象的内容不可改变,字符串是常量,所以每次进行字符串拼接操作会生成一个新的对象。这样既耗时又浪费内存,为了解决这个问题,可以使用 StringBuilder 类。

功能:可变字符序列(数组),它是一个类似String的字符串缓冲区,通过调用方法可以改变序列内容和长度。

构造方法:

  • public StringBuilder():构造一个空的StringBuilder容器。

  • public StringBuilder(String str):构造一个StringBuilder容器,并将字符串添加进去。

成员方法:

  • public StringBuilder append(...):添加任意类型数据的字符串形式,并返回当前对象自身。

  • public String toString():将当前StringBuilder对象转换为String对象。

public class TestStringBuilder {
    public static void main(String[] args){
        //创建StringBuilder对象
        StringBuilder builder = new StringBuilder();
        //添加任意字符
        builder.append("你是");
        builder.append(true);
        System.out.println(builder);
        
        //转换字符串
        String str = builder.toString();
    }
}

十一、包装类

1.什么是包装类?为什么要使用包装类?

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

2.装箱与拆箱

装箱可以将基本类型转换Wie对应的包装类对象。拆箱将包装类对象转换为基本类型。

如果对一个 包装类 进行修改,系统会自动完成拆箱和装箱操作。

valueOf或构造方法都可以进行装箱操作。

public class TestPack {
    public static void main(String[] args){
        int a = 1;
        //装箱
        Integer b = Integer.valueOf(a);
        //自动拆箱装箱
        b += 1;
        
    }
}

3.类型转换方法(基本类型和字符串转换)

  • public static byte parseByte(String s):将字符串参数转换为对应的byte基本类型。

  • public static short parseShort(String s):将字符串参数转换为对应的short基本类型。

  • public static int parseInt(String s):将字符串参数转换为对应的int基本类型。

  • public static long parseLong(String s):将字符串参数转换为对应的long基本类型。

  • public static float parseFloat(String s):将字符串参数转换为对应的float基本类型。

  • public static double parseDouble(String s):将字符串参数转换为对应的double基本类型。

  • public static boolean parseBoolean(String s):将字符串参数转换为对应的boolean基本类型。

注意如果转换类型必须为基本类型

温馨提示

  • 如果您对本文有疑问,请在评论部分留言,我会在最短时间回复。
  • 如果本文帮助了您,也请评论关注,作为对我的一份鼓励。
  • 如果您感觉我写的有问题,也请批评指正,我会尽量修改。

猜你喜欢

转载自www.cnblogs.com/lyxdw/p/11649759.html