Java基础(4):Java常见API

1 API

  • Application Program Interface(应用程序接口),是JDK中提供的可以使用的类。
  • jdk的安装目录下有个src.zip文件,其存放的就是所有java类的源文件。
  • 可以在官网在线查询各种API。

2 Object类

  • Object类是Java中的根类,即所有类、数组的父类。(接口除外)
  • Object类常用方法
    注意:可继承且不是final修饰的方法,都可以通过重写方法实现需要的功能。
Modifier and Type Method Description
public boolean equals​(Object obj) 判断指定对象与该对象是否相等(内存地址)
public String toString() 返回对象的字符串表示
protected void finalize() 垃圾回收
public native int hashCode() 返回对象的hashCode值
public final native Class<?> getClass() 返回对象的运行时类
equals方法
  • 子类可通过重写方法实现需要的功能。
    public class Person{
        ...
        //Override equals()方法
        public boolean equals(Object obj){
            if(this == obj){                    //同一对象
                return true;
            }
            if(obj instanceof Person){          //同类才能比较,保证可以强制类型转换
                Person person = (Person)obj;    //强制类型转换
                return this.name==person.name;
            }
            return false;
        }
    }
    
toString方法
  • 注意:输出语句中,输出对象会默认调用对象的toString方法。
    Person p = new Person();
    System.out.println(p);
    System.out.println(p.toString());    //两句输出结果一样
    

3 与用户互动

3.1 运行Java程序的参数

  Java程序的入口——main(String[] args)方法中参数可通过命令行指定。

  • 命令:java 文件名 参数值
    public class ArgsTest{
        public static void main(String[] args){
            // 输出args数组长度
            System.out.println(args.length);
            // 遍历args数组元素
            for(String arg : args){
                System.out.println(arg);
            }
        }
    }
    

3.2 Scanner类

  • Scanner类是基于正则表达式的文本扫描器。
  • 从文件、输入流、字符串中解析出基本类型值和字符串值。
  • Scanner类常用方法
Modifier and Type Method Description
public Scanner(InputStream source) 构造器1,接收输入流
public Scanner(File source) 构造器2,接收文件
public boolean hasNextXxx() 判断是否还有下一个输入项
public Xxx nextXxx() 获取下一个输入项
public Scanner useDelimiter(Pattern pattern) 设置特定输入分隔符

注意

  1. Xxx不存在时表示字符串String。
  2. 默认情况下,Scanner使用空白(包括空格、Tab空白、回车)作为输入分隔符。

4 系统相关

4.1 System类

  • System类代表程序所在系统。
  • System类的构造方法被private修饰,不能创建System类对象
  • System类中方法都是static方法,类名直接访问即可。
  • System类变量
Modifier and Type Field Description
public final static InputStream in 标准输入流
public final static PrintStream out 标准输出流
public final static PrintStream err 标准错误输出流
  • System类常用方法
Modifier and Type Method Description
static long currentTimeMillis() 返回当前日期的毫秒值
public static void gc() 垃圾回收
public static Map<String,String> getenv() 获取系统环境变量
public static Properties getProperties() 获取系统属性

4.2 Runtime类

  • Runtime类代表程序的运行时环境。
  • Runtime类的构造方法与System类似,不能new创建对象,可用getRuntime()方法创建对象。
  • Runtime类常用方法
Modifier and Type Method Description
public static Runtime getRuntime() 获得与程序关联的Runtime对象
public native void gc() 垃圾回收
public Process exec(String command) 启动进程运行操作系统的命令

5 字符串类

5.1 String类

  • Java中描述字符串的类。
  • 字符串是String类常量对象(本质是字符数组: private final char value[];),但String类的引用变量可以指向不同字符串常量。
  • String类常用方法
    • 构造器
Modifier and Type Method Description
public String(String original) 构造器1
public String(char value[]) 构造器2,将字符数组转化为字符串,不查询编码表。
public String(byte bytes[]) 构造器3,通过平台(OS)的默认字符集(GBK)解码指定的byte数组,构造新的String。
  • 其他方法
Modifier and Type Method Description
public int length() 返回字符串长度
public String substring(int beginIndex) 返回字符串的一部分
public char charAt(int index) 返回字符串第index个字符
public String toLowerCase() 返回全小写的字符串
public int indexOf(String str) 返回str第一次出现的位置
  • 正则表达式相关方法
Modifier and Type Method Description
public boolean matches(String regex) 匹配
public String[] split(String regex) 切割
public String replaceAll(String regex, String replacement) 替换

注意

  1. matches方法要从头到尾全匹配才返回true,原因是其方法本质是matches("^yourregex$")
  2. Java字符串中反斜杠(\)本身需要转义,因此两个反斜杠(\\)实际上相当于一个,如转义字符\d在Java中需要表示为\\d.
  3. 正则表达式内容参考这里

5.2 StringBuffer类

  • 字符串缓冲区,支持可变的字符串,提高字符串操作效率。
  • 采用可变数组实现char value[];
  • 线程安全类,保持同步,单线程情况下可用StringBuilder类代替。
  • 常用方法
Modifier and Type Method Description
public synchronized StringBuffer append(String str) 添加字符串
public synchronized StringBuffer insert(int offset, String str) 在offset位置插入
public synchronized StringBuffer reverse() 字符串反转
public synchronized StringBuffer delete(int start, int end) 删除
  • 如使用append方法,效率比String对象的+=高:
    public static void main(String[] args) {
        int[] data=new int[] {1,2,3,4};
        System.out.println(intToString(data));  //打印结果:[1,2,3,4]
    }
    public static String intToString(int[] arr){
    StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        for(int i=0;i<data.length;i++) {
            if(i==data.length-1) {
                buffer.append(data[i]).append("]");
    	}else {
    	    buffer.append(data[i]).append(",");
    	}
        }
        return buffer.toString();
    }
    

5.3 StringBuilder类

  • StringBuilder和StringBuffer基本类似,区别在于StringBuffer是线程安全的,而StringBuilder不是。

6 正则表达式相关类

6.1 Pattern类

  • Pattern对象是正则表达式编译后在内存中的表现形式。
编译
regex
Pattern对象
  • Pattern对象由static方法compile()获得。
  • Pattern类常用方法
Modifier and Type Method Description
public static Pattern compile(String regex) 编译regex存到Pattern对象
public static boolean matches(String regex, CharSequence input) 直接匹配
public Matcher matcher(CharSequence input) 创建Matcher对象
//字符串编译为Pattern对象
Pattern p = Pattern.compile("(?=.*[0-9a-zA-Z])[!-~]{8,16}");
//使用Pattern对象创建Matcher对象
Matcher matcher = p.matcher(".12345678");
//判断是否匹配
boolean b = matcher.matches();

上面3步等价于:

boolean b = Pattern.matches("(?=.*[0-9a-zA-Z])[!-~]{8,16}",".12345678");

6.2 Matcher类

  • 解释Pattern对字符序列进行匹配。
  • Matcher类没有默认构造器,只能通过Pattern对象的matcher()方法获得Matcher类对象。
  • Matcher类常用方法:
Modifier and Type Method Description
public boolean matches() 返回整个字符串与Pattern是否匹配
public boolean find() 返回字符串是否包含与Pattern匹配的子串
public String group() 返回上一次与Pattern匹配的子串
public Matcher reset(CharSequence input) 将该Matcher对象用于新的字符序列
Pattern p = Pattern.compile("(?=.*[0-9a-zA-Z])[!-~]{8,16}");
Matcher matcher = p.matcher(".123456789abcdef12345678");
boolean b = matcher.matches(); //是否完全匹配
boolean c = matcher.find();  //是否有子串匹配
System.out.println(b);  //输出false
System.out.println(c);  //输出true
System.out.println(matcher.group());  //输出上一次匹配子串:12345678

注意:find()和group()方法可以从目标字符串中依次取出特定字符串。

Pattern p = Pattern.compile("(?=.*[0-9a-zA-Z])[!-~]{8,16}");
Matcher matcher = p.matcher(".123456789abcdef12345678");
while(matcher.find()) {
	System.out.println(matcher.group());  //依次输出:.123456789abcdef 和 12345678
}

7 数学相关类

7.1 Math类

  • 构造器被定义成private,不能创建对象。
  • Math方法全是静态方法,由类直接调用。
  • Math类变量
Modifier and Type Field Description
public static final double PI 圆周率3.14159265358979323846
public static final double E 自然对数2.7182818284590452354
  • Math类常用方法
Modifier and Type Method Description
public static int abs(Xxx a) 返回a的绝对值
public static int round(double a) 四舍五入取整
public static double sqrt(double a) 计算平方根
public static double pow(double a, double b) 计算ab
public static double sin(double a) 计算正弦值
public static double asin(double a) 反正弦值

7.2 Random类

  • 用于生成伪随机数
  • 构造器
Modifier and Type Method Description
public Random() 当前时间为种子生成随机数
public Random(long seed) 显式传入long型种子
  • 常用方法
Modifier and Type Method Description
public Xxx nextXxx() 获取Xxx型伪随机数

7.3 BigDecimal类

  • 更加精确表示、计算浮点数。
  • 构造器:
Modifier and Type Method Description
public BigDecimal(String val) 传入字符串创建对象
public BigDecimal(BigInteger val) 传入BigInteger对象
  • 常用方法
Modifier and Type Method Description
public static BigDecimal valueOf(double/long val) 返回BigDecimal对象
public BigDecimal add(BigDecimal augend) 加法
public BigDecimal subtract(BigDecimal subtrahend) 减法
public BigDecimal multiply(BigDecimal multiplicand) 乘法
public BigDecimal divide(BigDecimal divisor) 除法

注意

  1. 创建BigDecimal对象时,不要直接使用double浮点数作为构造器参数,这样会造成精度丢失问题。解决:通过valueOf()方法转为BigDecimal对象。
    double a = 3.14159265357;
    BigDecimal bigA = BigDecimal.valueOf(a);
    
  2. double浮点数进行加、减、乘、除基本运算,先包装成BigDecimal对象,再调用相应方法。

8 日期、时间类

8.1 Date类

  • 毫秒值相关的Date类(日期精确到秒)属于java.util
  • 毫秒值:以公元1970年1月1日午夜0:00:00为时间原点。
    • 当前毫秒值:System.currentTimeMillis(),返回long类型.
  • Date类常用方法
Modifier and Type Method Description
public Date() 获得当前操作系统的时间和日期
public Date(long date) 传递毫秒值,将毫秒值转化为对应日期(Date)对象
public long getTime() 返回日期对象对应的毫秒值。
public void setTime(long time) 将毫秒值设置成日期对象

8.2 Calendar类

  • Calendar类是一个抽象类,直接已知子类:GregorianCalendar类
  • Calendar类写了静态方法getInstance(),直接返回子类对象,所以不需要new,子类对象可通过静态方法获得。
    Calendar cal=Calendar.getInstance();
    System.out.println(cal);
    
  • Calendar常用方法
Modifier and Type Method Description
public static Calendar getInstance() 获取子类实例
public final Date getTime() 抽取Date对象
public int get(int field) 返回指定日历字段的值
public void set(int field, int value) 将给定的日历字段设值
abstract public void add(int field, int amount) 对给定日历字段添加/减少指定值

日期计算实例

  1. 计算自己年龄
    System.out.println("输入出生日期(格式:yyyy-MM-dd): ");
    String birthDay=new Scanner(System.in).next();
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
    Date dateBirth = simpleDateFormat.parse(birthDay);  //字符串转Date
    long ms=System.currentTimeMillis()-dateBirth.getTime();  //毫秒值差值
    System.out.println("天数:"+ms/1000/60/60/24);
    System.out.println("年数:"+ms/1000/60/60/24/365);
    
  2. 闰年计算:日历设置到指定年份3月1日,add向前偏移1天,获取天数,29为闰年。
    while(true) {
       System.out.println("输入年份:");
       int year=new Scanner(System.in).nextInt();
       Calendar calendar=Calendar.getInstance();  //创建Calendar子类对象
       calendar.set(year, 2, 1);  //指定3月1号(国外是0-11月)
       calendar.add(Calendar.DAY_OF_MONTH, -1);  //向前偏移1天
       if(calendar.get(Calendar.DAY_OF_MONTH)==29) {
           System.out.println(year+" 是闰年!!");
       }else {
            System.out.println(year+" 不是闰年!!");				
       }
    }
    

9 格式化相关类

9.1 Format抽象类

  • Format是抽象类,已知直接子类有DateFormat类, MessageFormat类, NumberFormat类
  • Format类常用方法
Modifier and Type Method Description
public final String format (Object obj) 格式化对象生成字符串
public Object parseObject(String source) 字符串解析为对象

9.2 NumberFormat格式化数字

  • NumberFormat也是一个抽象基类,通过getXxxInstance()静态方法创建类对象。
  • NumberFormat类常用方法
Modifier and Type Method Description
public final static NumberFormat getIntegerInstance() 返回默认Locale的整数格式器
public static NumberFormat getInstance(Locale inLocale) 返回指定Locale的货币格式器
public final String format(double number) 将double数字格式化为字符串
public Number parse(String source) 将字符串解析为Number对象

9.3 DateFormat格式化日期、时间

  • DateFormat也是一个抽象类,通过getXxxInstance()方法获取对象。
  • DateFormat类常用方法
Modifier and Type Method Description
public final static DateFormat getDateInstance(int style, Locale aLocale) 返回日期格式器
public final static DateFormat getTimeInstance(int style, Locale aLocale) 返回时间格式器
public final String format(Date date) Date对象格式化为字符串
public Date parse(String source) 字符串解析为Date对象

注意:DateFormat类的parse()方法只能解析特定格式字符串,可使用SimpleDateFormat类灵活格式化和解析日期、时间。

日期格式化 :自己定义日期的格式。(日期转字符串)

  1. 创建SimpleDateFormat(java.text包)对象,构造方法中写入自定义日期格式(要求符合其Pattern规则).
  2. SimpleDateFormat对象调用format方法对日期格式化。
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日,hh:mm:ss");
    String date=sdf.format(new Date());
    System.out.println(date);  //输出如:2018年11月15日,10:14:38
    

字符串转日期

  1. 创建SimpleDateFormat(java.text包)对象,构造方法中指定日期格式。
  2. SimpleDateFormat对象调用parse方法,返回日期Date。
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf2.parse("2018-11-15"));  //输出如:Thu Nov 15 00:00:00 CST 2018
    

10 函数式接口

  • 函数式接口(Functional Interface):只包含一个抽象方法的接口。
  • 函数式接口可以用Lambda表达式创建匿名对象和重写接口唯一的抽象方法。
    Lambda表达式内容参考Java面向对象的2.2小节方法重写部分。

10.1 Consumer接口

  • 抽象方法
Modifier and Type Method Description
void accept(T t) 对给定参数执行此操作
  • 接口使用
  1. Iterable接口的forEach(Consumer action)方法
  2. Iterator接口的forEachRemaining(Consumer<? super E> action)方法
  3. 自定义的需要Consumer接口参数的方法。

10.2 Predicate接口

  • Predicate(谓词)抽象方法
Modifier and Type Method Description
boolean test(T t) 由参数计算谓词(true or false)
  • 接口使用
  1. Collection接口的removeIf(Predicate<? super E> filter)方法。
  2. 自定义的需要Predicate接口参数的方法。
    注意:函数式接口使用示例见Java集合2小节的遍历集合元素部分。

11 基本数据类型对象包装类

基本数据类型 字节型 短整型 整型 长整型 字符型 布尔型 浮点型 浮点型
数据类型 byte short int long char boolean float double
包装类 Byte Short Integer Long Character Boolean Float Double
  • 对象包装类在java.lang包中。
  • 对象包装类用于基本数据和字符串之间的转换。
    以整型为例:
    • 字符串 \rightarrow 基本数据类型
      使用方法public static int parseInt(String s);
      int a=Integer.parseInt("123");
      System.out.println(a/10);  //输出结果为12
      
    • 基本数据类型 \rightarrow 字符串
    1. 使用toString方法public static String toString(int i);
      int a=123;
      String b = Integer.toString(a);
      System.out.println(b+456); //输出结果为字符串123456
      
    2. 只需要基本数据+""(简单方法)
      int a = 12;
      String b = a+"";  //基本类型即转为字符串类型
      

注意:数据在byte范围内,JVM不会重新new对象。(见Integer源码)

Integer a2=127;
Integer a1=127;
System.out.println(a2==a1);  //true
System.out.println(a2.equals(a1));  //true
	
Integer b2=127;
Integer b1=127;
System.out.println(b2==b1);  //false
System.out.println(b2.equals(b1));  //true

猜你喜欢

转载自blog.csdn.net/new_delete_/article/details/83931085