第八章、常用类和JDK源码解读

本文深入探讨了Java中的String、StringBuilder/StringBuffer和包装类的使用,以及时间转化为字符串的方法,通过源码解读提供了更深层次的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、String类

/**
 * 测试String类的基本用法
 */
public class TestString {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }

    public static void test1(){
        //String类的定义
        String s1="abc";
        String s2=new String("abc");
        String s3="abc";
        String s4="aBC";

        //比较字符串
        System.out.println(s1==s2);     //判断是否为同一个字符串对象
        System.out.println(s1==s3);
        System.out.println(s1.equals(s2));      //判断字符串的值是否相等
        System.out.println(s1.equalsIgnoreCase(s4));        //忽略大小写,判断字符串的值是否相等
    }

    public static void test2(){
        String s1="0123456789,How are you,How old are you";

        System.out.println(s1.charAt(10));   //返回字符串中索引为4的字符
        System.out.println(s1.length());    //返回字符串的长度

        //字符串转换为数组
        char[] chars=s1.toCharArray();
        System.out.println(Arrays.toString(chars));
        String[] strs=s1.split(","); //可以传入正则表达式
        System.out.println(Arrays.toString(strs));

        //判断是否包含子字符串
        System.out.println(s1.indexOf("are"));  //从字符串头开始查找
        System.out.println(s1.lastIndexOf("are"));  //从字符串尾查找
        System.out.println(s1.contains("How"));
        System.out.println(s1.startsWith("0123"));
        System.out.println(s1.endsWith("are you"));

    }

    public static void test3(){
        String s1="0123456789,How are you";

        String s2=s1.replace(" ","&");
        System.out.println(s2);

        s2=s1.substring(4);
        System.out.println(s2);
        s2=s1.substring(4,10);      //[4,10) 不包含10这个位置
        System.out.println(s2);

        s2=s1.toLowerCase();
        System.out.println(s2);
        s2=s1.toUpperCase();
        System.out.println(s2);

        String s3=" How are you ";
        System.out.println(s3.trim());
    }
}

二、StringBuilder和StringBuffer类

/**
 * 测试可变字符序列StringBuilder的用法
 */
public class TestStringBuilder {

    public static void main(String[] args) {
        test1();
        test2();
    }
    public static void test1(){
        String s="";
        StringBuilder sb=new StringBuilder();
        StringBuffer sb2=new StringBuffer();

        sb.append("a");
        sb.append("b");
        sb.append("c").append("d").append("e");
        System.out.println(sb);

        sb2.append("学习Java");
        sb2.insert(0,"爱").insert(0,"我");
        System.out.println(sb2);
        sb2.delete(0,2);    //[0,2)删除字符
        System.out.println(sb2);
        sb2.deleteCharAt(0).deleteCharAt(0);
        System.out.println(sb2);

        System.out.println(sb2.reverse());  //字符串逆序
    }

    public static void test2(){
        //使用String进行字符串的拼接
        String str="";
        long num1=Runtime.getRuntime().freeMemory();    //获取JVM剩余的内存空间,单位是字节
        long time1=System.currentTimeMillis();      //获取当前时间,单位是毫秒

        for(int i=0;i<5000;i++){
            str+=i;     //相当于会产生5000个String对象
        }

        long num2=Runtime.getRuntime().freeMemory();    //获取JVM剩余的内存空间,单位是字节
        long time2=System.currentTimeMillis();      //获取当前时间,单位是毫秒

        System.out.println("String占用内存:"+(num1-num2));
        System.out.println("String占用时间:"+(time2-time1 ));

        System.out.println("======使用可变字符序列,完成拼接======");
        StringBuilder sb=new StringBuilder();
        long num3=Runtime.getRuntime().freeMemory();    //获取JVM剩余的内存空间,单位是字节
        long time3=System.currentTimeMillis();      //获取当前时间,单位是毫秒

        for(int i=0;i<5000;i++){
            sb.append(i);     
        }

        long num4=Runtime.getRuntime().freeMemory();    //获取JVM剩余的内存空间,单位是字节
        long time4=System.currentTimeMillis();      //获取当前时间,单位是毫秒

        System.out.println("String占用内存:"+(num3-num4));
        System.out.println("String占用时间:"+(time4-time3 ));
    }
}

三、包装类

/**
 * 测试包装类的用法,以Integer测试为主,其他包装类的用法相似
 */
public class TestInteger {

    public static void main(String[] args) {
        testInteger();
        testAutoBox();
        testCache();
    }

    /**
     * Integer的基本用法
     */
    public static void testInteger(){
        //基本数据类型转换为Integer对象
        Integer int1=Integer.valueOf(100);

        //包装类对象转成基本数据类型
        int int2=int1.intValue();
        long long1=int1.longValue();

        //字符串转换成Integer对象
        Integer int3=Integer.parseInt("324");
        System.out.println(int3);
        //包装类转成字符串
        System.out.println(int3.toString());
        //Integer能表示的最大数
        System.out.println("int能表示的最大数:"+Integer.MAX_VALUE);

    }

    /**
     * Integer的自动拆箱和自动装箱
     */
    public static void testAutoBox(){
        //自动装箱,编译器自动添加:Integer a=Integer.valueOf(100);
        Integer a=100;
        //自动拆箱,编译器自动添加:int b=a.intValue();
        int b=a;

        //空指针异常
        Integer c=null;
//        int d=c;
    }

    /**
     *包装类的缓存
     */
    public static  void testCache(){
        /*
        对于整型和char型所对应的包装类,对于-128~127之间的值,
        为了提高效率会进行缓存的处理
         */
        Integer a=Integer.valueOf(100);
        Integer b=100;
        System.out.println(a==b);

        Integer c=300;
        Integer d=300;
        System.out.println(c==d);
    }
}
/**
 * 自定义一个简单的包装类
 */
public class TestMyInteger {
    private int value;
    private static TestMyInteger[] cache=new TestMyInteger[256];

    private static final int LOW=-128;
    private static final int HIGH=127;

    //静态初始化块:是在类被加载的时候,初始化类的静态属性
    static{
        for(int i=TestMyInteger.LOW;i<=TestMyInteger.HIGH;i++){
            //索引0,-128+128
            cache[i+(-LOW)]=new TestMyInteger(i);
        }
    }

    private TestMyInteger(int i) {
        this.value=i;
    }

    public static TestMyInteger volueOf(int i){
        //如果在-128到127之间,返回数组中的缓存对象,否则创建新的对象
        if(i>=LOW&&i<=HIGH){
            return cache[i+(-LOW)];
        }else{
            return new TestMyInteger(i);
        }

    }

    public static void main(String[] args) {
        TestMyInteger a=TestMyInteger.volueOf(100);
        TestMyInteger b=TestMyInteger.volueOf(100);
        System.out.println(a==b);

        TestMyInteger c=TestMyInteger.volueOf(400);
        TestMyInteger d=TestMyInteger.volueOf(400);
        System.out.println(c==d);
    }
}

四、时间转化字符串

 

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 测试时间相关的类
 */
public class TestDate {
    public static void main(String[] args) throws ParseException {
        test1();
        test2();
        test3();
    }

    /**
     * 测试Date类
     */
    public static void test1(){
        //返回当前时刻的毫秒数
        long nowNum=System.currentTimeMillis();
        System.out.println(nowNum);

        Date d1=new Date();
        System.out.println(d1.getTime());

        //距离1970年150年后的日期,忽略闰年闰月
        Date d2=new Date(1000L*3600*24*365*150);
        System.out.println(d2);

        Date d3=new Date();
        //方法被废弃,可以用但不建议使用
        d3.getMonth();
        System.out.println(d3);

    }

    /**
     * 测试DateFormat类的使用,Date和字符串之间互相转换
     */
    public static void test2() throws ParseException {

        DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date d4=new Date(1000L*3600*24*365*150);
        String str=df.format(d4);
        System.out.println(str);

        String str2="2050-10-01 10:00:20";
        Date d5=df.parse(str2);
        System.out.println(d5);

        DateFormat df2=new SimpleDateFormat("yyyy年MM月dd日");
        System.out.println(df2.format(new Date()));

        //获取当前的时间是一年中的第几天
        DateFormat df3=new SimpleDateFormat("D");
        Date d6=new Date();
        System.out.println(df3.format(d6));
    }

    /**
     * 测试Calendar类,日历类的使用
     */
    public static void test3(){
        //月份:0-11,0:1月,1:2月...11:12月
        //星期:1-7,1:周日,2:周一...7:周六
        Calendar calendar=new GregorianCalendar(2999,9,10,11,25,40);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH);
        System.out.println(year+"-"+month);

        calendar.set(Calendar.YEAR,2026);
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.println(calendar.getTime());//返回对应的Date对象
        System.out.println(calendar.getTimeInMillis());//返回对应的毫秒数

        //日期的计算
        calendar.add(Calendar.DATE,1000);
        System.out.println(calendar.getTime());
        calendar.add(Calendar.YEAR,-30);
        System.out.println(calendar.getTime());

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值