JavaSE第五章 java常用API

5 第五章JavaAPI

是对java预先定义的类或接口, 功能 和方法功能的说明文档,目的是提供给开发人员进行使用帮助说明。

5.1 基本数据类型包装类

Java是一门面向对象的语言,但是其八种基本数据类型却是不面向对象的,这在实际使用中造成了很多不方便,为此引入了包装类的概念。

用途:

  1. 方便涉及到对象时的操作
  2. 包含基本数据类型的相关属性和操作
基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
character Character
boolean Boolean

5.2 Object

java.lang.Object

方法 作用
String toString() 返回描述该对象值的字符串。在自定义类中应覆盖这个方法
boolean equals(Object otherObject) 比较两个对象是否相等。在自定义类中应覆盖这个方法
Class getClass() int hashCode() 返回包含对象信息的类对象 返回对象的散列码
static wait() static notify() static notifyAll()

转成字符串toString()

返回描述该对象值的字符串

比较equals()

比较对象的地址是否相同 相当于 “==”

返回哈希值hashCode()

返回地址的hash值

5.3 Arrays

方法 作用
static String toString(type[] a) 返回包含a中数据元素的字符串
static void sort(type[] a) 采用优化的快速排序算法对数组进行排序
static void binarySearch(type[] a, type v) 使用二分搜索算法查找值v
static Boolean equals(type[] a, type[] b) 如果两个数字相同,返回true

5.3.1 转成字符串toString()

	public static void main(String[] args) {
    
    
        int[] a = {
    
    1,2,3};
        int[] b = {
    
    1,2,3};

        System.out.println(Arrays.equals(a, b)); //比较值
        System.out.println(a == b);//比较对象(也就是地址)
    }	

5.3.2 比较equals()

	public static void main(String[] args) {
    
    
        int[] a = {
    
    1,2,3};
        int[] b = {
    
    1,2,3};

        System.out.println(Arrays.equals(a, b)); //比较值
        System.out.println(a == b);//比较对象(也就是地址)
    }	

5.3.3 排序 sort()(快速排序)

对普通类型的排序
public class SortDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] a = {
    
    4,7,5,3,9,2,1,8};

//      Arrays.sort(a);//升序排序
        Arrays.sort(a,0,4);// 区间排序
        Integer[] b = {
    
    4,7,5,3,9,2,1,8};
        Arrays.sort(b); //也可以对Integer包装类数组进行排序
        System.out.println(Arrays.toString(b));
    }
}
对象数组的排序
public class SortDemo2 {
    
    
    public static void main(String[] args) {
    
    

        Student s1 = new Student("jim1",101);
        Student s2 = new Student("jim2",102);
        Student s3 = new Student("jim3",103);
        Student s4 = new Student("jim4",104);

        Student[] stuArr = {
    
    s1,s4,s3,s2};

        Arrays.sort(stuArr); // 对对象数组进行排序 
        /*
        	Student类实现了Comparator接口
        	sort排序调用了Student类中的compare()方法
        	要想用sort对对象数组进行排序,必须先实现ComParactor接口中的compare()方法。
        */

        System.out.println(Arrays.toString(stuArr));
    }
}

public class Student implements Comparator<Student> {
    
    

    public String name;
    public int id;

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

    public Student() {
    
    }

    /**
     * 基本数据类型的比较    用Comparator  接口
     * @param o1
     * @param o2
     * @return
     */
    @Override
    public int compare(Student o1, Student o2) {
    
    
//        return o1.id - o2.id;  // o1 - o2  正序
        return o2.id - o1.id; // 逆序
    }

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

自定义排序

自定义排序 必须实现Comparator接口

用name对Student数组进行排序

对字符串的比较排序会使用到String类实现Comparable接口中的compareTo()方法

/**
*自定义排序  必须实现Comparator接口
*/
public class SortName implements Comparator<Student> {
    
    

    public SortName() {
    
    
    }

    @Override
    public int compare(Student o1, Student o2) {
    
      // sort排序时会调用该函数
        return o2.name.compareTo(o1.name);  
    }
}
public class SortDemo2 {
    
    
    public static void main(String[] args) {
    
    

        Student s1 = new Student("jim1",101);
        Student s2 = new Student("jim2",102);
        Student s3 = new Student("jim3",103);
        Student s4 = new Student("jim4",104);

        Student[] stuArr = {
    
    s1,s4,s3,s2};
		
        //要把你写好的自定义排序类的对象传进去,这样他会自动调用你的自定义排序compare()方法
        Arrays.sort(stuArr,new SortName()); 

        System.out.println(Arrays.toString(stuArr));
    }
}
用id对Student数组进行排序
public class SortId implements Comparator<Student>  {
    
    
    public SortId() {
    
    
    }

    @Override
    public int compare(Student o1, Student o2) {
    
    
        return o1.id - o2.id;  // 正序 
    }
}
public class SortDemo2 {
    
    
    public static void main(String[] args) {
    
    

        Student s1 = new Student("jim1",101);
        Student s2 = new Student("jim2",102);
        Student s3 = new Student("jim3",103);
        Student s4 = new Student("jim4",104);

        Student[] stuArr = {
    
    s1,s4,s3,s2};
        
		//要把你写好的自定义排序类的对象传进去,这样他会自动调用你的自定义排序compare()方法
        Arrays.sort(stuArr,new SortId());

        System.out.println(Arrays.toString(stuArr));
    }
}

5.3.4 查找 binarySearch()(二分)

public class SearchDemo {
    
    
    public SearchDemo() {
    
    }
    public static void main(String[] args) {
    
    

        //要使用二分查找,必须先排序。
        int[] a = {
    
    5,6,3,8,7,9,2,4};
        Arrays.sort(a); //排序

        System.out.println(Arrays.toString(a));
        int index = Arrays.binarySearch(a,7); //把 数组 和 查找的值 传进去
        System.out.println("index = " + index); // 返回下标, 如果为负数,就说明没找到
    }
}
手撕二分查找
/**
* 二分查找的前提是 目前查找的数组有序。
* 把num和mid中间下标的值进行比较,如果num比mid处的值小,那说明目标num在mid的左边。
* 如果大,则正好相反。每次循环都会砍掉一半,对剩下的另一半进行查找
*/
    public static int search(int[] arr,int num){
    
    
        int low = 0,
            high = arr.length-1
            ,mid = 0;

        while (low<high){
    
    
            mid = (low+high) >>> 1;  //>>>1 位运算  右移一位,相当于除2
            if (arr[mid]>num){
    
     //取左边
                high = mid - 1;
            }else if (arr[mid]<num){
    
     //去右边
                low = mid + 1;
            }else {
    
    
                return mid;
            }
        }
        return -mid;
    }

5.4 String

方法 作用
char charAt(int index) 返回给定位置的代码单元
boolean equals(Object other) 如果字符串与other相等,返回true
boolean equalsIngoreCase(String other) 忽略大小写
int length() 返回字符串的长度
String substring(int beginIndex) 返回一个新字符串,包含原始字符串从beginIndex到串尾或到endIndex-1的所有代码单元
String substring(int beginIndex, int endIndex)
String toLowerCase() 返回小写字符串
String toUpperCase() 返回大写字符串
int indexOf(String str[, int fromIndex])
int lastIndexOF(String str[, int fromIndex])
返回第一个/最后一个子串的位置,从起始位置或者fromIndex开始

5.4.1 字符串的初始化

public class StringDemo {
    
    
    public StringDemo() {
    
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
    
    
        /*
            字符串初始化
         */
        char[] c = {
    
    'a','b','c'}; // 字符的默认值为 ' ' 空格字符
        String s = new String();  //默认值为 “”  空串
        String s1 = new String(c); //将字符数组转换成字符串。
        String s2 = new String(c,0,2); //截取字符数组并转换成字符串
        System.out.println("s = " + s );
        System.out.println("s1 = " + s1);
        System.out.println("s2 = " + s2);

        byte[] b = s1.getBytes();//使用平台的默认字符集将此 String 编码为 byte 序列,并返回
        System.out.println(Arrays.toString(b));

        b = s1.getBytes("utf-8");
        System.out.println(Arrays.toString(b));//使用指定的字符集将此 String 编码为 byte 序列

        String encode = new String(b); //解码  使用平台的默认字符集将此 byte序列解码为String 
        System.out.println(encode);
        
        String encode1 = new String(b,"utf-8"); // 使用指定的字符集 进行解码
        System.out.println(encode1);

        String encode2 = new String(b,"gbk"); // 使用指定的字符集 进行解码
        System.out.println(encode2);
    }
}

5.4.2 判断方法

public class StringIsDemo {
    
    
    public StringIsDemo() {
    
    }
    public static void main(String[] args) {
    
    

        String s = "abcdefg";
        String ss = "abcdefg";
        String s1 = new String("abcdefg");
        String s2 = "AbcDefG";
        //当初始化是直接赋值时, ss会去常量池里找有没有“abcdefg” ,有就会指向它, 没有就会创建一个新的。
        System.out.println(s == ss);
        System.out.println(s.equals(s1)); //重写了Object的equals方法 , 比较 字符串里的值
        System.out.println(s1.equalsIgnoreCase(s2)); //比较的时候忽略大小写
        System.out.println("a".compareTo("b")); //-1  "a" < "b"
        System.out.println();

        String sub = "cde";
        System.out.println(s1.contains(sub)); //判断是否包含目标子串
        System.out.println(s1.contains("abc"));
        System.out.println();

        System.out.println(s1.isEmpty());  //判断是否为空字符串
        System.out.println("".isEmpty());  //"" 和 null 不一样
        System.out.println();

        System.out.println(s2.startsWith("ab")); //判断是否以该字符串开头
        System.out.println(s.startsWith("ab", 3));  //判断是否以该字符串开头,以指定的下标为开头
        System.out.println(s.endsWith("g"));  //判断是否以该字符串结尾
        System.out.println();
    }
}

5.4.3 获取方法

public class StringGetDemo {
    
    
    public StringGetDemo() {
    
    }
    public static void main(String[] args) {
    
    

        String s = "abcdefghci";
                //  123456789
          /*数组是array.length
            字符串是 string.length() ,但是调用的length()方法中获取的是字符数组的length(chs.length);   chs是字符数组
            集合是 size()
         */
        System.out.println("长度 s.length() = " + s.length()); //数组是array.length

        System.out.println(s.charAt(8)); //返回下标处的字符
        System.out.println(s.indexOf("c")); // 返回目标字符串第一次出现时所在的下标  从前往后
        System.out.println(s.indexOf("c", s.indexOf("c"))); // 返回第二次出现的下标
        s.lastIndexOf("c"); //从后往前  返回第一次出现目标字符串的下标

        System.out.println(s.substring(5));  // 从5开始截取到字符串末尾
        System.out.println(s.substring(5, 8)); //左闭右开
    }
}

5.4.4 转换方法

public class StringTransmitDemo {
    
    

    public StringTransmitDemo() {
    
    
    }

    public static void main(String[] args) {
    
    

        char[] chs = "abcdefg".toCharArray(); //将字符串转换成字符数组

        // 将其他类型转换成字符串
        System.out.println(String.valueOf(chs));   //将字符数组 转 字符串
        System.out.println(new String(chs));  //将字符数组 转 字符串

        String s = "AedFeggDW";
        System.out.println(s.toLowerCase());  //全部转成小写
        System.out.println(s.toUpperCase());  //全部转成大写

        s = "a:bc:def:ghij";
        System.out.println(s.concat("xxxxxxxxxxxxxx"));  //拼接  a:bc:def:ghijxxxxxxxxxxxxxx
        System.out.println(Arrays.toString(s.split(":"))); //分隔  并转换成字符串数组 ,正则表达式
        //[a, bc, def, ghij]


        
    }

}

5.4.5 替换方法

		//替换
		String s = "a:bc:def:ghij";
        System.out.println(s.replace(':', '|')); // a|bc|def|ghij
        System.out.println(s.replaceAll(":", "")); // abcdefghij
        s = "a2b3cd4efghijk66";
        s.replaceAll("\\d","");  //正则表达式

5.4.6 正则表达式

public class Reg {
    
    
    public Reg() {
    
    }
    public static void main(String[] args) {
    
    
        String s = "33";

        System.out.println("1  " + s.matches("\\d"));
        System.out.println("2  " + s.matches("[2-4]"));
        System.out.println("3  " + s.matches("[245]"));
        System.out.println("4  " + s.matches("\\D"));  //非数字
        System.out.println("5  " + s.matches("[2-4]?")); //一次或一次也没有
        System.out.println("6  " + s.matches("[2-4]*")); //零次或多次
        System.out.println("7  " + s.matches("[2-4]+")); //一次或多次
        System.out.println("8  " + s.matches("[2-4]{2}")); //恰好n次
        System.out.println("9  " + s.matches("[2-4]{3,}")); //至少n次
        System.out.println("10  " + s.matches("[2-4]{2,5}")); //至少n次,最多5次
        System.out.println();

        String ss = "abcdef";
        System.out.println("1  " + ss.matches("[A-z]*"));
        System.out.println("2  " + ss.matches("[A-z,1-9]{1,4}"));
        System.out.println();

        String sss = "";
        System.out.println("1  " + ss.matches("\\w"));//匹配字母和数字
        System.out.println("1  " + ss.matches("\\W"));
        System.out.println("2  " + ss.matches("\\s")); //匹配空白字符
        System.out.println("2  " + ss.matches("\\S"));
        System.out.println();

        //邮箱
        String str = "[email protected]";
        System.out.println(str.matches("\\w{1,16}@\\w{2,6}\\.(com|com\\.cn)"));

        //电话
        String mobile = "13279370686";
        System.out.println(mobile.matches("^1[3597]\\d{9}$"));

        //匹配以zh开头 并以3结尾的且不含空白字符的字符串
        String ssss = "zh16843444514";
        System.out.println(ssss.matches("^(zh)\\S*3$"));

    }

}

在这里插入图片描述

在这里插入图片描述

5.4.7 可变字符序列(字符串)

StringBuffer
  1. append()
  2. insert()
  3. delete()
  4. replace()
  5. reverse()
  6. substring()
/**
*可变字符串的操作
*/
public static void main(String[] args) {
    
    

        StringBuffer s = new StringBuffer("asdccdff");
        s.append(6); //追加
        System.out.println(s);
        s.insert(0,"aa");  //插入 在指定下标处插入
        System.out.println(s);
        s.deleteCharAt(0);  //删除指定下标的字符
        System.out.println(s);
        s.delete(0,3);    // 删除指定区间的字符
        System.out.println(s);
        s.replace(0,2,"aaaaaaaaa"); //替换区间内的字符串
        System.out.println(s);
        s.reverse();  //反转字符串
        System.out.println(s);

        System.out.println(s.substring(0, 5)); //截取 指定区间的字符串, 源字符串s不变
        System.out.println(s);

    }

StringBuilder
public static void main(String[] args) {
    
    

        StringBuilder s = new StringBuilder("shddbfabfka");
        //基本操作和StringBuffer一样
        /**
         * String:是字符常量,适用于少量的字符串操作的情况
         * StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况
         * StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况
         */

    }

5.5 Random

方法 作用
Random() 构建一个新的随机数生成器
setSeed() 重置种子数
int nextInt(int n) 返回一个 0 ~ n-1之间的随机数

5.6 Date 日期

5.6.1 Date

Date类代表当前系统时间

Date date = new Date();
Date date = new Date(long d);

5.6.2 Calendar

Calendar c = Calendar.getInstance();

Calendar calendar1 = new GregorianCalendar();
Calendar calendar = Calendar.getInstance(); //同上, 两者一样
        calendar.set(Calendar.YEAR,2050); //更改 年份
        System.out.println(calendar.getTime()); //时间戳
        System.out.println(calendar.getTimeInMillis()); //时间戳

        System.out.println(calendar.getWeekYear());
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));
        System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));
        System.out.println(calendar.get(Calendar.YEAR)); //1
        System.out.println(calendar.get(Calendar.MONTH)+1); //2
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); //5
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY)); //11
        System.out.println(calendar.get(Calendar.MINUTE)); // 12
        System.out.println(calendar.get(Calendar.SECOND)); // 13

5.6.3 SimpleDateFormat 日期格式化

SimpleDateFormat form = new SimpleDateFormat(String format) //format 格式 yyyy-MM-dd

日期转换成字符串

Date now = new Date();
form.format(now);

字符串转换成日期

form.parse("2000-12-25") //必须带"-"格式

5.7 BigInteger

实现任意精度的整数运算.

不可变的任意精度的整数。所有操作中,都以二进制补码形式表示 BigInteger(如 Java 的基本整数类型)。BigInteger 提供所有 Java 的基本整数操作符的对应物,并提供 java.lang.Math 的所有相关方法。另外,BigInteger 还提供以下运算:模算术、GCD 计算、质数测试、素数生成、位操作以及一些其他操作。

在Java中,由CPU原生提供的整型最大范围是64位long型整数。使用long型整数可以直接通过CPU指令进行计算,速度非常快。

如果我们使用的整数范围超过了long型怎么办?这个时候,就只能用软件来模拟一个大整数。java.math.BigInteger就是用来表示任意大小的整数。BigInteger内部用一个int[]数组来模拟一个非常大的整数:

BigInteger bi = new BigInteger("1234567890");
System.out.println(bi.pow(5)); 
// 2867971860299718107233761438093672048294900000

BigInteger做运算的时候,只能使用实例方法, 不能使用运算符,例如,加法运算:

BigInteger i1 = new BigInteger("1234567890");
BigInteger i2 = new BigInteger("12345678901234567890");
BigInteger sum = i1.add(i2); // 12345678902469135780

long型整数运算比,BigInteger不会有范围限制,但缺点是速度比较慢。

也可以把BigInteger转换成long型:

BigInteger i = new BigInteger("123456789000");
System.out.println(i.longValue()); // 123456789000
System.out.println(i.multiply(i).longValueExact()); // java.lang.ArithmeticException: BigInteger out of long range

使用longValueExact()方法时,如果超出了long型的范围,会抛出ArithmeticException

BigIntegerIntegerLong一样,也是不可变类,并且也继承自Number类。因为Number定义了转换为基本类型的几个方法:

  • 转换为bytebyteValue()
  • 转换为shortshortValue()
  • 转换为intintValue()
  • 转换为longlongValue()
  • 转换为floatfloatValue()
  • 转换为doubledoubleValue()

因此,通过上述方法,可以把BigInteger转换成基本类型。如果BigInteger表示的范围超过了基本类型的范围,转换时将丢失高位信息,即结果不一定是准确的。如果需要准确地转换成基本类型,可以使用intValueExact()longValueExact()等方法,在转换时如果超出范围,将直接抛出ArithmeticException异常。

5.7.1 构造方法

BigInteger(byte[] val)` 将包含 BigInteger 的二进制补码表示形式的 byte 数组转换为 BigInteger。
BigInteger(int signum, byte[] magnitude) 将 BigInteger 的符号-数量表示形式转换为 BigInteger。
BigInteger(int bitLength, int certainty, Random rnd) 构造一个随机生成的正 BigInteger,它可能是一个具有指定 bitLength 的素数。
BigInteger(int numBits, Random rnd) 构造一个随机生成的 BigInteger,它是在 0(2numBits - 1)(包括)范围内均匀分布的值。
BigInteger(String val) 将 BigInteger 的十进制字符串表示形式转换为 BigInteger。
BigInteger(String val, int radix) 将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger。

5.7.2 方法

方法 作用 例子
valueOf( ) 将普通的数值转成BigInteger BigInteger bigInt = BigInteger.valueOf(111);

5.8 BigDecimal

BigInteger类似,BigDecimal可以表示一个任意大小且精度完全准确的浮点数。

BigDecimal bd = new BigDecimal("123.4567");
System.out.println(bd.multiply(bd)); // 15241.55677489

BigDecimalscale()表示小数位数,例如:

BigDecimal d1 = new BigDecimal("123.45");
BigDecimal d2 = new BigDecimal("123.4500");
BigDecimal d3 = new BigDecimal("1234500");
System.out.println(d1.scale()); // 2,两位小数
System.out.println(d2.scale()); // 4
System.out.println(d3.scale()); // 0

通过BigDecimalstripTrailingZeros()方法,可以将一个BigDecimal格式化为一个相等的,但去掉了末尾0的BigDecimal

BigDecimal d1 = new BigDecimal("123.4500");
BigDecimal d2 = d1.stripTrailingZeros();
System.out.println(d1.scale()); // 4
System.out.println(d2.scale()); // 2,因为去掉了00

BigDecimal d3 = new BigDecimal("1234500");
BigDecimal d4 = d3.stripTrailingZeros();
System.out.println(d3.scale()); // 0
System.out.println(d4.scale()); // -2

如果一个BigDecimalscale()返回负数,例如,-2,表示这个数是个整数,并且末尾有2个0。

BigDecimal做加、减、乘时,精度不会丢失,但是做除法时,存在无法除尽的情况,这时,就必须指定精度以及如何进行截断:

BigDecimal d1 = new BigDecimal("123.456");
BigDecimal d2 = new BigDecimal("23.456789");
BigDecimal d3 = d1.divide(d2, 10, RoundingMode.HALF_UP); // 保留10位小数并四舍五入
BigDecimal d4 = d1.divide(d2); // 报错:ArithmeticException,因为除不尽

还可以对BigDecimal做除法的同时求余数, 调用divideAndRemainder()方法时,返回的数组包含两个BigDecimal,分别是商和余数,其中商总是整数,余数不会大于除数。

我们可以利用这个方法判断两个BigDecimal是否是整数倍数:

BigDecimal n = new BigDecimal("12.75");
BigDecimal m = new BigDecimal("0.15");
BigDecimal[] dr = n.divideAndRemainder(m);
if (dr[1].signum() == 0) {
    
    
    // n是m的整数倍
}

比较BigDecimal

在比较两个BigDecimal的值是否相等时,要特别注意,使用equals()方法不但要求两个BigDecimal的值相等,还要求它们的scale()相等:

BigDecimal d1 = new BigDecimal("123.456");
BigDecimal d2 = new BigDecimal("123.45600");
System.out.println(d1.equals(d2)); // false,因为scale不同
System.out.println(d1.equals(d2.stripTrailingZeros())); // true,因为d2去除尾部0后scale变为2
System.out.println(d1.compareTo(d2)); // 0

必须使用compareTo()方法来比较,它根据两个值的大小分别返回负数、正数和0,分别表示小于、大于和等于。

总是使用compareTo()比较两个BigDecimal的值,不要使用equals()!

如果查看BigDecimal的源码,可以发现,实际上一个BigDecimal是通过一个BigInteger和一个scale来表示的,即BigInteger表示一个完整的整数,而scale表示小数位数:

public class BigDecimal extends Number implements Comparable<BigDecimal> {
    
    
    private final BigInteger intVal;
    private final int scale;
}

BigDecimal也是从Number继承的,也是不可变对象。

小结

BigDecimal用于表示精确的小数,常用于财务计算;

比较BigDecimal的值是否相等,必须使用compareTo()而不能使用equals()

5.9 System

public class SystemDemo {
    
    

    public SystemDemo() {
    
    
    }

    public static void main(String[] args) {
    
    
        //System.out;  //PrintStream
        //System.in
        System.out.println();
		
        //System.arraycopy() 数组拷贝 
        //所谓的动态数组就是用arraycopy()实现的
        int[] srcArr = {
    
    1,2,3,4,5,6,7,8,9};
        int[] desArr = new int[5];
        System.arraycopy(srcArr,2,desArr,0,3);
        System.out.println(Arrays.toString(desArr));

        //System.currentTimeMillis()  获取当前系统时间
        System.out.println(System.currentTimeMillis());
//        Date date = new Date();

        //System.getenv("Path")  根据环境变量的名字获取环境变量。
        System.out.println(System.getenv());
        System.out.println(Arrays.toString(System.getenv("Path").split(";")));

        //用于获取系统的所有属性。属性分为键和值两部分,它的返回值是Properties。
        System.out.println(System.getProperties());
        
//        System.exit(0); //停止虚拟机

        //测试运行时间
        //测试 +  拼接字符串
        String str = "";
        Long time = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
    
    
            str += "a";
        }
        Long time1 = System.currentTimeMillis();
        System.out.println("测试 + 拼接1000次的效率  " + (time1-time) +" 毫秒");

        //测试  String.concat()
        str = "";
        time = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
    
    
            str = str.concat("a");
        }
        time1 = System.currentTimeMillis();
        System.out.println("测试  String.concat()拼接1000次的效率  " + (time1-time) +" 毫秒");

        //测试  StringBuffer
        StringBuffer strbf = new StringBuffer("");
        time = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
    
    
            strbf.append("a");
        }
        time1 = System.currentTimeMillis();
        System.out.println("测试  StringBuffer拼接1000次的效率  " + (time1-time) +" 毫秒");


        System.out.println(666);
    }
}

5.10 Class

方法 作用
String getName() 返回这个类的名字
static Class forName(String className) 返回描述类名为className的Class对象
Object newInstance() 返回这个类的一个新实例
Field[] getFields()
Field[] getDeclareFields() getFields()
getFields()返回一个包含Field对象的数组,这些对象记录了这个类或其超类的公有域
getDeclareFields()返回的Field对象记录了这个类的全部域
Method[] getMethods()
Method[] getDeclareMethods()
getMethods()返回一个包含Method对象的数组,这些对象记录了这个类或其超类的公用方法
getDeclareMethods()返回的Field对象记录了这个类的全部方法
Constructor[] getConstructors()
Constructor[] getDeclareConstructors()
getConstructors()返回一个包含Constructor对象的数组,这些对象记录了这个类的公有构造器
getDeclareConstructors()返回的Constructor对象记录了这个类的全部构造器

猜你喜欢

转载自blog.csdn.net/qq_37079157/article/details/109689554