Java中的常用类

一,包装类
    八大数据类型提供了相应的引用数据类型,成为包装类。
    byte——————————Byte
    short——————————Short
    int———————————Integer
    long——————————Long
    float—————————— Float
    double—————————Double
    char——————————Character
    boolean————————Boolean
    
    常用方法:
    toString()    valueOf    parseXX
    
    常见题型:
        //示例一
        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=127;
        Integer i6=127;
        System.out.println(i5==i6);true

        //示例四
        Integer i7=128;
        Integer i8=128;
        System.out.println(i7==i8);false

        //示例五
        Integer i9=127;
        Integer i10=new Integer(127);
        System.out.println(i9==i10);false

        //示例六
        Integer i11=127;
        int i12=127;
        System.out.println(i11==i12);true

        //示例七
        Integer i13=128;
        int i14=128;
        System.out.println(i13==i14);true
java->Integer类源码:
private static class IntegerCache {
        static final int low = -128;
        static final int high ;
        static final Integer cache [];
        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM. getSavedProperty ( "java.lang.Integer.IntegerCache.high" );
            if (integerCacheHighPropValue != null ) {
                try {
                    int i = parseInt (integerCacheHighPropValue);
                    i = Math. max (i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math. min (i, Integer. MAX_VALUE - (- low ) -1);
                } catch ( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
            cache = new Integer[( high - low ) + 1];
            int j = low ;
            for ( int k = 0; k < cache . length ; k++)
                cache [k] = new Integer(j++);
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache . high >= 127;
        }
        private IntegerCache() {}
    }
在Integer类中如果有参构造器中的数值不大于127那么将不会创建对象。



二,String
    常见方法:
    length 获取字符个数
    charAt 获取指定索引处的字符
    toUpperCase转大写
    toLowerCase转小写
    indexOf获取字符或字符串第一次出现的索引,如果找不到返回-1
    lastIndexOf获取字符或字符串最后一次出现的索引,如果找不到返回-1
    startsWith判断是否以xx开头
    endsWith判断是否以XX结尾
    regionMatches判断是否某范围内的子串一致
    contains 判断子串是否存在,返回true|false
    compareTo 比较两个字符串大小
    equals/equalsIgnoreCase判断字符串内容是否相等
    substring截取子串
    replace/replaceAll替换
    trim去前后空格
    split拆分
    concat拼接字符串
    toCharArray转换成字符数组

    创建对象:
    方式1:直接赋值
    String s  = "hello";
    先去常量池查看是否有“hello”字符序列,如果没有,则创建,如果有直接引用该地址,s指向的是常量池的对象
    
    方式2:通过调用构造器
    String s = new String("hello");
    需要在堆中创建对象,该对象维护了一个value属性,value指向常量池的“hello”,如果常量池中没有“hello”,则创建,再指向;
    如果已经有了,则直接用value指向,s指向的是堆中的对象

内存图:




    在String类的源码中给出了相应的解释:
/** The value is used for character storage. */
    private final char value [];

Strings are constant; their values cannot be changed after they are created.

进阶:
    结果为:good and gest




三,StingBuffer
    保存字符串变量,可以对字符串进行基本操作。
    默认定义为16长度的char[]数组
    也可以自己定义长度
    或者定义一个字符串,默认长度变成字符串的长度+16。

    常用方法:(这些操作实际上是直接对值进行改变,不用定义变量接收)
    append 增加任意类型
    replace 替换指定索引段的字符串
    delete 删除
    indexOf 查找字符对应的索引
    insert  插入
    reverse  反转

四,StringBuilder
    方法与String一致。
    String与Stringbulider的比较:
                             共同点                    版本        线程安全(同步)        效率
     
    StringBuffer    保存可变字符串          老         安全                           较低
    
    

    StringBuilder    保存可变字符串          新        不安全                        较高


五,Match
    主要包含了一些包含数学运算的静态方法。
    例如:
    sqrt    开方
    pow     求幂
    ceil    向上取整
    floor    向下取整
    round    四舍五入
    abs    取绝对值
    random     随机数
    max    最大值
    min    最小值

六,Arrays
    用于对数组的管理

    sort(T[]) :对数组的元素进行自然排序,要求元素必须实现了Comparable
    sort(T[],Comparator):对数组的元素进行定制排序,元素本身可以不实现Comparable
    binarySearch(T[],key):对数组通过二分搜索法进行查找,如果key找到了,返回索引,否则返回负数。要求:要查找的数组必须提前排好序!

    copyOf(T[],length):复制数组的元素
    equals(T[],T[]):判断两个数组的内容是否相等
    fill(T[],key):填充数组的各元素值为key
    toString():将数组各元素进行拼接,返回String

七,BigDecimal和BigInteger
    add 加法
    substract减法
    multiply乘法

    divide除法,注意:可以添加参数2设置四舍五入模式

八, 时间类
包括Date , SimpleDateFormat, Calendar, LocalDate, LocalTime, LocalDateTime, DateTimeFormat, Instant...

测试各个时间类的常用方法及类型转换

@Test
      public void testDate() {
          // 方式一:调用无参构造器(获取系统当前时间)
         Date d1 = new Date();
         System. out .println(d1);
          // 方式二:调用有参构造器(获取距离基准时间指定毫秒数的日期对象) 不建议使用!
         Date d2 = new Date(123456789);
         System. out .println(d2);
          // 调用常见方法:getTime
         System. out .println( "d1:" + d1.getTime());
         System. out .println( "d2:" + d2.getTime());
     }
运行结果:
Fri Mar 30 19:09:09 CST 2018
Fri Jan 02 18:17:36 CST 1970
d1:1522408149265
d2:123456789


// 测试使用默认格式的SimpleDateFormat类
      @Test
      public void testDateFormat1() throws ParseException {
          // 创建日期对象:Fri Mar 30 15:16:41 CST 2018
         Date d = new Date();
          // 根据默认格式创建SimpleDateFormat对象
         SimpleDateFormat sdf = new SimpleDateFormat();
          // 格式日期:Date————>String
         String format = sdf.format(d);
         System. out .println(format);
          // 解析日期:String————>Date
         String s = "18-12-10 下午3:22" ;
         Date parse = sdf.parse(s);
         System. out .println(parse);
     }
运行结果:
18-3-30 下午7:17
Mon Dec 10 15:22:00 CST 2018


// 测试使用自定义格式的SimpleDateFormat类
      @Test
      public void testDateFormat2() throws ParseException {
          // 创建日期对象:Fri Mar 30 15:16:41 CST 2018
         Date d = new Date();
          // 根据指定格式创建SimpleDateFormat对象
         SimpleDateFormat sdf = new SimpleDateFormat( "yyyy年MM月dd日 a hh小时mm分钟ss秒" );
          // 格式日期:Date————>String
         String format = sdf.format(d);
         System. out .println(format);
          // 解析日期:String————>Date
         String s = "2018年03月30日 下午 06小时54分钟38秒" ;
         Date parse = sdf.parse(s);
         System. out .println(parse);
     }
运行结果:
2018年03月30日 下午 07小时17分钟44秒
Fri Mar 30 18:54:38 CST 2018


@Test
      public void TestCalendar() {
          // 1.获取Calendar对象
         Calendar c = Calendar. getInstance ();
         System. out .println(c);
          // 2.通过调用方法获取各个日历字段
         System. out .println( "年:" + c.get(Calendar. YEAR ));
         System. out .println( "月:" + c.get(Calendar. MONTH ));
         System. out .println( "日:" + c.get(Calendar. DAY_OF_MONTH ));
         System. out .println( "小时:" + c.get(Calendar. HOUR ));
         System. out .println( "分钟:" + c.get(Calendar. MINUTE ));
         System. out .println( "秒:" + c.get(Calendar. SECOND ));
         System. out .println( "星期:" + c.get(Calendar. DAY_OF_WEEK ));
     }
运行结果:
java.util.GregorianCalendar[time=1522408696183,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2018,MONTH=2,WEEK_OF_YEAR=13,WEEK_OF_MONTH=5,DAY_OF_MONTH=30,DAY_OF_YEAR=89,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=7,HOUR_OF_DAY=19,MINUTE=18,SECOND=16,MILLISECOND=183,ZONE_OFFSET=28800000,DST_OFFSET=0]
年:2018
月:2
日:30
小时:7
分钟:18
秒:16
星期:6


@Test
      public void testInstant() {
          // 1.获取Instant对象
         Instant instant = Instant. now ();
          // 2.Instant和Date之间的转换
          // ①Instant——>Date
         Date date = Date. from (instant);
          // ②Date——>Instant
         Instant instant2 = date.toInstant();
         System. out .println(instant2);
     }
运行结果:
2018-03-30T11:18:57.428Z


@Test
      public void test1() {
          // 1.获取LocalDateTime对象
         LocalDateTime now = LocalDateTime. now ();
         System. out .println(now);
          // 2.获取各个日历字段
         System. out .println(now.getYear());
         System. out .println(now.getMonthValue());
         System. out .println(now.getMonth());
         System. out .println(now.getDayOfMonth());
         System. out .println(now.getHour());
         System. out .println(now.getMinute());
         System. out .println(now.getSecond());
         System. out .println(now.getDayOfWeek());
     }
运行结果:
2018-03-30T19:20:34.854
2018
3
MARCH
30
19
20
34
FRIDAY


// 测试DateTimeFormatter
      @Test
      public void test2() {
         LocalDateTime now = LocalDateTime. now ();
          // 根据指定的格式创建DateTimeFormatter对象
         DateTimeFormatter dtf = DateTimeFormatter
                  . ofPattern ( "yyyy年MM月dd日 HH小时mm分钟ss秒" );
          // 格式日期:Date——>String
         String format = dtf.format(now);
         System. out .println(format);
          // 解析日期:String——>Date
         LocalDateTime parse = LocalDateTime. parse ( "2018年03月30日 16小时02分钟06秒" ,
                  dtf);
         System. out .println(parse);
     }
运行结果:
2018年03月30日 19小时21分钟01秒
2018-03-30T16:02:06







常用时间类的使用:

//测试LocalDate类★ ★★★★★★★★★★★★★★★★★★★★★★★★
      @Test
      public void testLocalDate() {
          // 获取当前日期(只包含日期,不包含时间)
         LocalDate date = LocalDate. now ();
         System. out .println(date);
          // 获取日期的指定部分
         System. out .println( "year:" +date.getYear());
         System. out .println( "month:" +date.getMonth());
          System. out .println( "day:" +date.getDayOfMonth());
          System. out .println( "week:" +date.getDayOfWeek());
          // 根据指定的日期参数,创建LocalDate对象
         LocalDate of = LocalDate. of (2010, 3, 2);
         System. out .println(of);
     }
      // 测试LocalTime类
      @Test
      public void testLocalTime() {
          // 获取当前时间(只包含时间,不包含日期)
         LocalTime time = LocalTime. now ();
         System. out .println(time);
          // 获取时间的指定部分
         System. out .println( "hour:" + time.getHour());
         System. out .println( "minute:" + time.getMinute());
         System. out .println( "second:" + time.getSecond());
         System. out .println( "nano:" + time.getNano());
          // 根据指定的时间参数,创建LocalTime对象
         LocalTime of = LocalTime. of (10, 20, 55);
         System. out .println(of);
     }
      // 测试LocalDateTime类
      @Test
      public void testLocalDateTime() {
          // 获取当前时间(包含时间+日期)
         LocalDateTime time = LocalDateTime. now ();
          // 获取时间的指定部分
         System. out .println( "year:" + time.getYear());
         System. out .println( "month:" + time.getMonthValue());
         System. out .println( "day:" + time.getMonth());
         System. out .println( "day:" + time.getDayOfMonth());
         System. out .println( "hour:" + time.getHour());
         System. out .println( "minute:" + time.getMinute());
         System. out .println( "second:" + time.getSecond());
         System. out .println( "nano:" + time.getNano());
          // 根据指定的时间参数,创建LocalTime对象
         LocalDateTime of = LocalDateTime. of (2020, 2, 2, 10, 20, 55);
         System. out .println(of);
     }
      // 测试MonthDay类:检查重复事件
      @Test
      public void testMonthDay() {
         LocalDate birth = LocalDate. of (1994, 12, 12);
         MonthDay birthMonthDay = MonthDay. of (birth.getMonthValue(), birth.getDayOfMonth());
         LocalDate now = LocalDate. now ();
         MonthDay current = MonthDay. from (now);
          if (birthMonthDay.equals(current)) {
              System. out .println( "今天生日" );
         } else {
              System. out .println( "今天不生日" );
         }
     }
      // 测试是否是闰年 ★ ★★★★★★★★★★★★★★★★★★★★★★★★
      @Test
      public void testIsLeapYear() {
         LocalDate now = LocalDate. now ();
         System. out .println(now.isLeapYear());
     }
      // 测试增加日期的某个部分
      @Test
      public void testPlusDate() {
         LocalDate now = LocalDate. now ();
         LocalDate plusYears = now.plusYears(-3);
         System. out .println(plusYears);
     }
      // 使用plus方法测试增加时间的某个部分
      @Test
      public void testPlusTime() {
         LocalTime now = LocalTime. now ();
         LocalTime plusHours = now.plusHours(1);
         System. out .println(plusHours);
     }
      // 使用minus方法测试查看一年前和一年后的日期
      @Test
      public void testMinusTime() {
         LocalDate now = LocalDate. now ();
         
         LocalDate minus = now.minus(1, ChronoUnit. YEARS );
         
         LocalDate minus2 = now.minusYears(1);
         System. out .println(minus2);
     }
      //测试时间戳类:Instant ,相当于以前的Date类 ★ ★★★★★★★★★★★★★★★★★★★★★★★★
      @Test
      public void testInstant() {
         
         Instant now = Instant. now ();
         System. out .println(now);
         
          //与Date类的转换
         Date date = Date. from (now);
         System. out .println(date);
         
         Instant instant = date.toInstant();
         
         System. out .println(instant);
         
         
     }
      //测试DateTimeFormatter ★ ★★★★★★★★★★★★★★★★★★★★★★★★
      @Test
      public void testDateTimeFormatter() {
         
         DateTimeFormatter pattern = DateTimeFormatter. ofPattern ( "MM-dd yyyy HH:mm:ss" );
         
          //将字符串转换成日期
         
         LocalDateTime parse = LocalDateTime. parse ( "03-03 2017 08:40:50" , pattern);
         System. out .println(parse);
         
          //将日期转换成字符串
         
         String format = pattern.format(parse);
         System. out .println(format);
     }









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值