美文网首页
Java基础3-常用的API

Java基础3-常用的API

作者: MononokeHime | 来源:发表于2018-11-09 11:40 被阅读0次

常用的API介绍

Object

位于java.lang.Object。所有类都是直接或者间接继承Object
Object类的方法:

  • public int hashCode():返回对象的hash码值,hash值是根据哈希算法计算出来的一个值,这个值根地址有关,但是不是实际的地址值。

  • public final class getClass():返回此对象的运行时类(与反射有关)。

Student c = new Student();
Class c = s.getClass();
String str = c.getName();
System.out.println(str); // Student
  • public String toString():返回对象的字符串表示(与Python中的__str__类似)。
  • public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。默认的Object的equals是比较的地址值。

==
基本类型:比较的就是值
引用类型:比较的就是地址值是否相等

class Student{
    int age;
    String name;

    public Student(int age,String name){
    this.age = age;
    this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        Student s = (Student) obj;
        if (this.name.equals(s.name) && this.age == s.age) {
            return true;
        } else {
            return false;
        }
    }
}

class HelloWorld{
    public static void main(String[] args) {
        Student s1 = new Student(20,"Liang");
        Student s2 = new Student(20,"Liang");
        System.out.println(s1.equals(s2));
    }
}

注意:String类的equals方法是重写Object类的,比较的是字符串的内容是否相同

  • protected void finalize():当垃圾回收器确定不存在对该对象的更多引用时,由垃圾回收器调用此方法,用于垃圾回收。但是什么时候回收不确定。(一般不会用到)
  • protected Object clone():相当于Python中的copy.deepcopy()

String

字符串就是由多个字符组成的一串数据。可以看成是一个字符数组。
字符串是常量,他们的值一旦创建之后就不能更改。

String str = "abc";

类似于

char data[] = {'a','b','c'};
String str = new String(data)

构造方法:

  • public String():空构造
  • public String(char[] value):把字符数组转成字符串
  • public String(char[] value,int index,int count):把字符数组的一部分转为字符串

注意:

String s = "hello";
s += "world";
sout(s); // helloworld

内存图


image.png

区别?

String s = new String("abc"); // 创建了2个对象, abc存在方法区的常量池中,堆中开辟了存放abc的地址
String s = "abc"; // abc存在方法区的常量池中

String s1 = new String("abc"); // 创建了2个对象
String s2 = "abc";
String s3 = "abc";
System.out.println(s1 == s2);  // false
System.out.println(s2 == s3);  //true
System.out.println(s1.equals(s2));  // true
image.png

字符串拼接的小知识

String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1+s2);  // flase
System.out.println(s3 == "hello"+"world");  // true

结论:
字符串如果是变量相加,先开空间,再拼接
字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则就创建

常用方法:

  • boolean equals(Object obj);
  • blloean equalsIngoreCase(String str):比较字符串的内容,区分大小写
  • boolean contains(String str):判断大字符串是否包含小字符串
  • boolean startsWith(String str):判断字符串是否以某个字符串开头
  • boolean endsWith(String str):判断字符串是否以某个字符串结尾
  • boolean isEmpty():判断字符串是否为空
  • int length():获取字符串的长度
  • char charAt(int index):获取指定索引位置的字符
  • int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引(为什么是int类型,原因是char可以转成int,'a'和97是一致的,这里可以写'a'或者97)
  • int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引
  • int indexOf(int ch,int fromIndex):
  • int indexOf(String str,int fromIndex):
  • String substring(int start):从指定位置开始截取字符串,默认到结尾
  • String substring(int start,int end)
  • char[] toStringArray():将字符串转换为字符数组
  • String toLowerCase():
  • int compareTo(String str):

StringBuffer

我们如果对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。而StringBuffer就可以解决这个问题。
StringBuffer是线程安全的可变字符序列。
StringBuffer默认开辟16长的空间,可以理解成数组的扩容操作。可以自己看元源码。

StringBuffer sb1 = new StringBuffer();
System.out.println(sb1.capacity()); // 16
StringBuffer sb2 = new StringBuffer(50);
System.out.println(sb2.capacity()); // 50

// 添加数据
System.out.println(sb1.append("hello")); // hello
System.out.println(sb1.append("world"));  // helloworld
System.out.println(sb1);  // helloworld

StringBuilder

此类提供一个与StringBuffer兼容的API,但不能保证同步。该类被设计用作StringBuffer的一个简单替换,用在字符串缓存区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer要快。

String,StringBuffer和StringBuilder区别?

  • String是内容不变的,而StringBuffer和StringBuilder都是内容可变的
  • StringBuffer是同步的,数据安全,效率低;StringBuilder是不同步的,数据不安全,效率高

String和StringBuffer作为形参传递的问题
String作为形参传递,效果跟基本类型传递一样
StringBuffer作为形参传递,仍是引用传递

public class StringBufferDemo {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "world";
        System.out.println(s1 + "---" + s2);// hello---world
        change(s1, s2);
        System.out.println(s1 + "---" + s2);// hello---world

        StringBuffer sb1 = new StringBuffer("hello");
        StringBuffer sb2 = new StringBuffer("world");
        System.out.println(sb1 + "---" + sb2);// hello---world
        change(sb1, sb2);
        System.out.println(sb1 + "---" + sb2);// hello---worldworld

    }

    public static void change(StringBuffer sb1, StringBuffer sb2) {
        sb1 = sb2;
        sb2.append(sb1);
    }

    public static void change(String s1, String s2) {
        s1 = s2;
        s2 = s1 + s2;
    }
}

Arrays

针对数组进行操作的工具类,比如排序和查找。
java.util.Arrays

  • public static String toString(int[] a):将数组转换为字符串
  • public static void sort(int[] a):对数组进行升序排列
  • public static int binarySearch(int[] a,int key):二分查找

基本数据类型和对应的包装类

为了对基本数据类型进行更多的操作,更方便的操作,Java针对每一种基本数据类型提供了对应的类类型。称为包装类类型。

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

Integer

  • public Integer(int value):将一个int包装成Integer类
  • public Integer(String s):将一个可以转成int的字符串包装成Integer类,例如"100"
  • public static String toBinaryString(int i):将10进制转为二进制
  • public static final int MAX_VALUE:获取Integer最大值

String和int之间转换
String->int:public static int parseInt(String s)
int->String:public static String toString(int i)

自动装箱和自动拆卸

自动装箱:把基本类型转换为包装类类型
自动拆箱:把包装类类型转换为基本类型

Integer i = 100;
i+=200;

等价于

Integer i = Integer.valueOf(100); // 自动装箱
i = Integer.valueOf(i.intValue()+200); // 先自动拆箱,再自动装箱

小整数常量池

Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2);  // false

Integer i3 = new Integer(128);
Integer i4 = new Integer(128);
System.out.println(i3 == i4);  // false

Integer i5 = 128;
Integer i6 = 128;
System.out.println(i5 == i6);  // false

Integer i7 = 127;  // Integer i7 = Integer.valueOf(127);
Integer i8 = 127;
System.out.println(i7 == i8);  // true

通过查看源码,调用valueOf,针对-128~127之间的数据,做了一个缓冲池,如果数据是该范围,每次并不创建新的空间

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
 }

Character

用于判断字符的类

  • public static boolean isUpperCase(char ch)
  • public static boolean isLowerCase(char ch)
  • public static char toUpperCase(char ch)
  • public static char toLowerCase(char ch)

Random

  • public Random():没有种子,用的是默认种子,即当前系统时间的毫秒值
  • public Random(long seed):给定指定的种子,每次得到的随机数相同

System

  • public static void gc():运行垃圾回收器。
  • public static void exit(int status):终止当前的java虚拟机(直接退出程序)。参数用作状态码;根据惯例,非0的状态码表示异常终止。
  • public static long currentTimeMillis():返回以毫秒为单位的当前时间(用于统计程序运行时间)
  • public static void arraycopy(Object src,int srcPos,Object dest,int length):从指定源数组中复制一个数组

BigInteger

支持更大的整数

BigInteger bi = new BigInteger(100000000000);

BigDecimal

任意精度的有符号的数

System.out.println(0.09+0.01);  // 0.09999999999999999
System.out.println(1.0-0.32);  // 0.6799999999999999

BigDecimal bd1 = new BigDecimal("0.09");
BigDecimal bd2 = new BigDecimal("0.01");
System.out.println(bd1.add(bd2));

Date

java.util.Date

import java.util.Date;

class HelloWorld {
    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        Date d = new Date(time);  // 将毫秒值转为date
        System.out.println(d);  // Fri Nov 09 15:56:11 CST 2018
        System.out.println(d.getTime());  // 获取当前时间的毫秒值,1541750217767
    }
}

DateFormat

java.text.DateFormat
格式化日期

import java.util.Date;
import java.text.DateFormat;

class HelloWorld {
    public static void main(String[] args) throws ParseException {
// Date -> String
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY年MM月dd日 HH:mm:ss");
        String s = sdf.format(d);
        System.out.println(s);  // 2018年11月09日 17:02:33

// String -> Date
        String str = "2008-08-08 12:12:12";
        SimpleDateFormat sdf2 = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Date dd = sdf2.parse(str);
        System.out.println(dd);  // Sun Dec 30 12:12:12 CST 2007

    }
}

Calendar

抽象类

import java.util.Calendar;

class HelloWorld {
    public static void main(String[] args) {
        Calendar rightNow = Calendar.getInstance(); // 获取子类对象(多态实现)
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH);
        int date = rightNow.get(Calendar.DATE);
        System.out.println(year+"年"+(month+1)+"月"+date+"日");  // 2018年11月9日
    }
}

相关文章

网友评论

      本文标题:Java基础3-常用的API

      本文链接:https://www.haomeiwen.com/subject/fbswxqtx.html