java作业

比较字符串

特性char *String (Java)StringBuilder (Java)StringBuffer(Java)String (JS)
可变可变的, 可以进行单字节的操作不可变,拼接需要重新重新创建对象可变,但是初始长度默认为16个字符,扩容会影响性能可变,但是初始长度默认为16个字符,扩容会影响性能不可变,拼接需要重新重新创建对象
易操作不易操作,提供的api较少容易操作,API丰富容易操作,API丰富容易操作,API丰富容易操作,API丰富
内存高效内存高效内存不高效内存不高效内存不高效内存不高效
并发安全线程安全线程不安全线程不安全线程安全JS执行引擎是单线程的,所以没有这个问题
使用场景频繁频繁频繁不频繁频繁

效率比较


public class Test {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        testString();
        System.out.println("Java String 耗时:"+ (System.currentTimeMillis() - start) + "ms");

        start = System.currentTimeMillis();
        testStringBuffer();
        System.out.println("StringBuffer 耗时:"+ (System.currentTimeMillis() - start) + "ms");

        start = System.currentTimeMillis();
        testStringBuilder();
        System.out.println("StringBuilder 耗时:"+ (System.currentTimeMillis() - start) + "ms");

    }

    public static String testString(){
        String result = "";
        for (int i = 10000; i < 50000; i++) {
            result += "AA" + i + "BB";
        }
        return result;
    }

    public static String testStringBuffer(){
        StringBuffer result = new StringBuffer();
        for (int i = 10000; i < 50000; i++) {
            result.append("CC").append(i).append("DD")  ;
        }
        return result.toString();
    }

    public static String testStringBuilder(){
        StringBuilder result = new StringBuilder();
        for (int i = 10000; i < 50000; i++) {
            result.append("EE").append(i).append("FF")  ;
        }
        return result.toString();
    }
}

let prev = new Date().getTime();
let result = "";
for (let i = 10000; i < 50000; i++) {
    result += "AA" + i + "BB";
}

console.log(" JS String 耗时 : " + new Date().getTime() - prev + "ms");

Java String 耗时:9317ms
StringBuffer 耗时:3ms
StringBuilder 耗时:3ms
JS String 耗时 : 13ms

正则

邮政编码:^\d{6}$

区号-座机号码:0\d{2,3}-[1-9]\d{6,7}

手机号码:^[1]+[3,5]+\d{9}$

测试代码:


import java.util.regex.Pattern;

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

        String content = "315826";
        String pattern = "^\\d{6}$";

        System.out.println(Pattern.matches(pattern, content));

        pattern = "0\\d{2,3}-[1-9]\\d{6,7}";
        content = "020-8888888";
        System.out.println(Pattern.matches(pattern, content));

        pattern = "^[1]+[3,5]+\\d{9}$";
        content = "13189457961";
        System.out.println(Pattern.matches(pattern, content));
    }
    
}

运行截图:

点赞

发表评论

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像

Title - Artist
0:00