JAVA常用类

目录

字符串相关的类:String

String不同实例化方式的对比

String不同拼接操作的对比

String常用方法

String与基本数据类型包装类的转换

String与char[]之间的转换

String与byte[]之间的转换

String,StringBuffer,StringBuilder的异同

StingBuffer类的常用方法

JDK8之前日期时间API

数组课后算法题

SimpleDateFormat的使用: SimpleDateFormat 对日期Date类的格式化和解析

Calendar日历类(抽象类)的使用

JDK8中新日期时间API

方法

Instant类的使用

DateTimeFormatter类:格式化或解析日期、时间

Java比较器

方式一:

方式二:

其他常用类

Math类


字符串相关的类:String

String不同实例化方式的对比

  • 通过字面量定义的方式:此时的s1和s 2的数据javaEE声明在方法区中的字符串常量池中。
  • 通过new +构造器的方式:此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值。

String不同拼接操作的对比

  • 基本数据类型传的是存储的数据,引用数据类型存储的是地址值

String常用方法

String与基本数据类型包装类的转换

String与char[]之间的转换

String与byte[]之间的转换

  • 说明:解码时,要求解码使用的字符集必须与编码时使用的字符集一致, 否则会出现乱码

String,StringBuffer,StringBuilder的异同

StingBuffer类的常用方法

JDK8之前日期时间API

 


      //构造器一:Date():创建一个对应当前时间的Date对象
        Date date1 = new Date();
        System.out.println(date1.toString());//Sat Feb 16 16:35:31 GMT+08:00 2019
​
        System.out.println(date1.getTime());//1550306204104
​
        //构造器二:创建指定毫秒数的Date对象
        Date date2 = new Date(155030620410L);
        System.out.println(date2.toString());
​
        //创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(35235325345L);
        System.out.println(date3);//1971-02-13
​
        //如何将java.util.Date对象转换为java.sql.Date对象
        //情况一:
//        Date date4 = new java.sql.Date(2343243242323L);
//        java.sql.Date date5 = (java.sql.Date) date4;
        //情况二:
        Date date6 = new Date();
        java.sql.Date date7 = new java.sql.Date(date6.getTime());

数组课后算法题

1.将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg"反转为"albfedcg”

//方式一:转换为char[];
 public String reverse(String str, int startIndex, int endIndex) {
     if (str!=null){
         char[] arr = str.toCharArray();
         for (int x = startIndex, y = endIndex; x < y; x++, y--) {
             char temp = arr[x];
             arr[x] = arr[y];
             arr[y] = temp;
         }
         return new String(arr);
     }
     return null;
 }

 //方式二:使用String的拼接操作
 public String reverse1(String str, int startIndex, int endIndex){
    if (str!=null){
        //截取前面两个字符串
        String reverseStr=str.substring(0,startIndex);
        //遍历需要逆置的字母,添加的到取出来的地方去
        for (int i=endIndex;i>=startIndex;i--){
            reverseStr+=str.charAt(i);
        }
        reverseStr +=str.substring(endIndex+1);
        return  reverseStr;
    }
    return null;
 }

 //方法三:使用StringBuffer/StringBuilder替换String
 public String reverse2(String str, int startIndex, int endIndex){
     StringBuilder b=new StringBuilder(str.length());
     b.append(str.substring(0,startIndex));
     for (int i=endIndex;i>=startIndex;i--){
         b.append(str.charAt(i));
     }
     b.append(str.substring(endIndex+1));
     return b.toString();
 }

2.获取一个字符串在另一一个字符串中出现的次数。比如:获取" ab"在"abkkcadkabkebfkabkskab”中出现的次数. 



class qq {
 public int getCount(String maxStr, String minStr) {
     int maxLength = maxStr.length();
     int minLength = minStr.length();
     int index = 0;
     int count = 0;
     if (maxLength >= minLength) {
     /*
     方式一
        * //让序列号初始化等于第一次所找到所要寻找字符串的第一个位置
​
            while ((index = maxStr.indexOf(minStr)) != -1) {
                count++;
                //让长字符改变,变为前一个minStr的序号加上minStr的长度之后的子串
                maxStr = maxStr.substring(index + minStr.length());
            }
​
         */
            //方式二:对方式一的改进
            while ((index = maxStr.indexOf(minStr, index)) != -1) {
                count++;
                //让序列号在前一个找到的基础上上要寻找字符的长度
                index += minLength;
            }
​
            return count;
        } else {
            return 0;
        }
    }
}

3.获取两个字符串中最大相同子串。比如:str1 = "abcwerthelloyuiodef;str2 = "cvhellobnm"。提示:将短的那个串进行长度依次递减的子串与较长的串比较。

class getMaxString {
    public String getMaxSameString(String str1, String str2) {
        if (str1 != null && str2 != null) {
            String maxStr = (str1.length() >= str2.length()) ? str1 : str2;
            String minStr = (str1.length() < str2.length()) ? str1 : str2;
            int length = minStr.length();
            for (int i = 0; i < length; i++) {
                for (int x = 0, y = length - i; y <= length; x++, y++) {
                      String subStr = minStr.substring(x, y);
                    if (maxStr.contains(subStr)) {
                        return subStr;
                    }
                }
            }
        }
        return null;
    }
}


 

SimpleDateFormat的使用: SimpleDateFormat 对日期Date类的格式化和解析

 

1.两个操作: 1.1 格式化:日期 --->字符串

                       1.2 解析:格式化的逆过程,字符串 ---> 日期

2.SimpleDateFormat的实例化

public void testSimpleDateFormat() throws ParseException {
        //实例化SimpleDateFormat:使用默认的构造器
        SimpleDateFormat sdf = new SimpleDateFormat();
​
        //格式化:日期 --->字符串
        Date date = new Date();
        System.out.println(date);
​
        String format = sdf.format(date);
        System.out.println(format);
​
        //解析:格式化的逆过程,字符串 ---> 日期
        String str = "19-12-18 上午11:43";
        Date date1 = sdf.parse(str);
        System.out.println(date1);
​
        //*************按照指定的方式格式化和解析:调用带参的构造器*****************
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format1 = sdf1.format(date);
        System.out.println(format1);//2019-02-18 11:48:27
        //解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
        //否则,抛异常
        Date date2 = sdf1.parse("2020-02-18 11:48:27");
        System.out.println(date2);
    }

练习一:字符串"2020-09-08"转换为java.sql.D ate
​
练习二:"三天打渔两天晒网"   1990-01-01  xxxx-xx-xx 打渔?晒网?

Calendar日历类(抽象类)的使用

 

 //1.实例化
        //方式一:创建其子类(GregorianCalendar)的对象
        //方式二:调用其静态方法getInstance()
        Calendar calendar = Calendar.getInstance();
//        System.out.println(calendar.getClass());
​
        //2.常用方法
        //get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
​
        //set()
        //calendar可变性
        calendar.set(Calendar.DAY_OF_MONTH,22);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
​
        //add()
        calendar.add(Calendar.DAY_OF_MONTH,-3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
​
        //getTime():日历类---> Date
        Date date = calendar.getTime();
        System.out.println(date);
​
        //setTime():Date ---> 日历类
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

JDK8中新日期时间API

 

  •  LocalDateTime用得多一些

方法

 

  • of():设置指定的年、月日、时、分秒。 没有偏移量
  • withXxx():设置相关的属性,体现不可变性

 

LocalDate、LocalTime、LocalDateTime 的使用
    说明:
        1.LocalDateTime相较于LocalDate、LocalTime,使用频率要高
        2.类似于Calendar
     */
    @Test
    public void test1(){
        //now():获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
​
        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);
​
        //of():设置指定的年、月、日、时、分、秒。没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
        System.out.println(localDateTime1);
​
​
        //getXxx():获取相关的属性
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getDayOfWeek());
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getMonthValue());
        System.out.println(localDateTime.getMinute());
​
        //体现不可变性
        //withXxx():设置相关的属性
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);
        System.out.println(localDate1);
​
​
        LocalDateTime localDateTime2 = localDateTime.withHour(4);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);
​
        //不可变性
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);
​
        LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);
    }

Instant类的使用

 

 

 public void test2(){
        //now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//2019-02-18T07:29:41.719Z

        //添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00

        //toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数  ---> Date类的getTime()
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  -->Date(long millis)
        Instant instant1 = Instant.ofEpochMilli(1550475314878L);
        System.out.println(instant1);
    }

DateTimeFormatter类:格式化或解析日期、时间

 

public void test3(){
//        方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);//2019-02-18T15:42:18.797

        //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797");
        System.out.println(parse);

//        方式二:
//        本地化相关的格式。如:ofLocalizedDateTime()
//        FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//2019年2月18日 下午03时47分16秒


//      本地化相关的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2019-2-18


//       重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2019-02-18 03:52:09

        //解析
        TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");
        System.out.println(accessor);

    }

Java比较器

  • 使用两个接口中的任何一个: Comparable 或Comparator

方式一:

Comparable接口的使用举例:  自然排序

1.像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式。

2.像String、包装类重写compareTo()方法以后,进行了从小到大的排列

3. 重写compareTo(obj)的规则:
    如果当前对象this大于形参对象obj,则返回正整数,
    如果当前对象this小于形参对象obj,则返回负整数,
    如果当前对象this等于形参对象obj,则返回零。

4. 对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)方法。
   在compareTo(obj)方法中指明如何排序
例子:
   //指明商品比较大小的方式:按照价格从低到高排序,再按照产品名称从高到低排序
public int compareTo(Object o) {
//        System.out.println("**************");
        if(o instanceof Goods){
            Goods goods = (Goods)o;
            //方式一:
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else{
//                return 0;
               return -this.name.compareTo(goods.name);
            }
            //方式二:
//           return Double.compare(this.price,goods.price);
        }
//        return 0;
        throw new RuntimeException("传入的数据类型不一致!");
    }
}

方式二:

 

 public int compare(Object o1, Object o2) {
                if(o1 instanceof Goods && o2 instanceof Goods){
                    Goods g1 = (Goods)o1;
                    Goods g2 = (Goods)o2;
                    if(g1.getName().equals(g2.getName())){
                        return -Double.compare(g1.getPrice(),g2.getPrice());
                    }else{
                        return g1.getName().compareTo(g2.getName());
                    }
                }
                throw new RuntimeException("输入的数据类型不一致");
            }

其他常用类

Math类

 

来都来了记得点个赞拉~~~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值