String、Date、對象排序、System、Math、BigInteger與BigDecimal

String

1.String聲明為final,表示不可被繼承
2.String實(shí)現(xiàn)了Serializable接口:表示字符串支持序列化;實(shí)現(xiàn)Comparable接口(比較對象大?。硎維tring可以比較大小
3.String內(nèi)部定義的final char[ ] value用于存儲字符串?dāng)?shù)據(jù)
4.String:表示不可變字符序列。簡稱:不可變性
體現(xiàn)(1)對當(dāng)前字符串重新賦值時(shí),需要重新指定內(nèi)存區(qū)域賦值,不能使用原有的value賦值
(2)當(dāng)對現(xiàn)有字符串進(jìn)行連接操作時(shí),也需要指定新的內(nèi)存區(qū)域賦值,不能使用原有的value賦值
(3)當(dāng)調(diào)用String的replace()方法修改指定字符或字符串時(shí),也需要重新指定內(nèi)存區(qū)域賦值,不能使用原有的value賦值
5.通過字面量方式(區(qū)別于new)給一個(gè)字符串賦值,此時(shí)的字符串值聲明在字符串常量池中
6.字符串常量池不會存儲相同內(nèi)容的字符串

String的兩種創(chuàng)建方式

1.字面量方式:String s = "abc";數(shù)據(jù)在方法區(qū)的字符串常量中,共享目的
2.new + 構(gòu)造器:String s = new String("abc");數(shù)據(jù)在堆空間中

        String s1 = new String("abc");
        String s2 = "abc";
        System.out.println(s1==s2);//false比較地址
        System.out.println(s1.equals(s2));//true比較值
        Person p1 = new Person("tom",12);
        Person p2 = new Person("tom",12);

        System.out.println(p1==p2);//false,比較對象地址
        System.out.println(p1.equals(p2));//false,比較對象值

        //new Person("tom",12);,即已字面量方式給name賦值,因此name值相等
        System.out.println(p1.name==p2.name);//true,比較字面量name
        System.out.println(p1.name.equals(p2.name));//true,比較字面量name

        p1.name = "jerry";
        System.out.println(p1.name==p2.name);//false,常量池中重新創(chuàng)建了jerry的常量
例題:String s = new String("abc");中創(chuàng)建了幾個(gè)對象

兩個(gè):一個(gè)是堆空間中new結(jié)構(gòu);另一個(gè)是char[ ]對應(yīng)的常量池中的數(shù)據(jù)“abc”

String不同拼接操作的對比

(1)常量和常量的拼接結(jié)果在常量池,且常量池中不會存在相同內(nèi)容的常量
(2)只要拼接字符串中有一個(gè)是變量(如果該變量前有final,即表示常量,則他不存在于隊(duì)中,而是存在于方法區(qū)的常量池中),就存在于堆中,相當(dāng)于new了一個(gè)對象

        final String str2 = "Web";//表示常量
        String str3 = "javaEEWeb";
        String str4 = "javaEE"+str2;//存在于常量池中
        System.out.println(str3 == str4);//true

(3)若拼接后的結(jié)果調(diào)用intern()方法,則返回值是位于常量位置的

        String s1 = "javaEE";
        String s2 = "Web";

        String s3 = "javaEEWeb";
        String s4 = "javaEE" + "Web";
        String s5 = s1 + "Web";
        String s6 = "javaEE" + s2;
        String s7 = s1 + s2;

        String s8 = s7.intern();
        System.out.println(s3 == s4);//true
        System.out.println(s3 == s5);//false
        System.out.println(s3 == s6);//false
        System.out.println(s3 == s7);//false
        System.out.println(s5 == s6);//false
        System.out.println(s5 == s7);//false

        System.out.println(s3 == s8);//true

例題:

public class Test01 {
    String str  = new String("good");
    char[] ch = {'t','e','s','t'};

    public void change(String str,char ch[]){
        str = "test ok";
        ch[0] = 'b';
    }

    public static void main(String[] args) {
        Test01 t = new Test01();
        t.change(t.str,t.ch);
        System.out.println(t.str);//good
        System.out.println(t.ch);//best
    }
}

String常用不熟悉方法

        String s = "  He  l l o  ";
        String s1 = s.trim();
        System.out.println(s1);//去除字符串前后空格

        String s2 = "java";
        String concat = s2.concat("EE");
        System.out.println(concat);//字符串進(jìn)行拼接(javaEE)

        String s3 = "abc";
        String s4 = "abefghf";
        System.out.println(s3.compareTo(s4));//返回兩者比較的差值(-2)

        System.out.println(s3.equals(s4));//比較字符串內(nèi)容是否相同(false)
        System.out.println(s3.contains("e"));//字符串是否包含指定字符(false)
        System.out.println(s4.indexOf("e"));//字符串第一次出現(xiàn)指定字符的位置(2)
        System.out.println(s4.indexOf("g",2));//從指定索引開始查找指定字符串所在索引位置,記錄位置從前往后(4)

        String s5 ="helloword";
        System.out.println(s5.lastIndexOf("wo"));//指定字符在該字符串最右邊出現(xiàn)的索引,但該位置記錄仍然是從前往后計(jì)數(shù)(5)
        System.out.println(s5.lastIndexOf("el",7));//從指定索引反向查找指定字符串所在索引,記錄位置從前往后(1)

        //什么時(shí)候indexOf(str)和lastIndexOf(str)返回值相同
        //1.存在唯一的str(查找的字符只有一個(gè))  2.空字符串時(shí)

        String s6 = "123";
        String replace = s6.replace('1', '2');
        System.out.println(replace);//將1替換為2,但原字符串仍不改變
//正則表達(dá)式替換,匹配,切片
//replaceAll(regex,replacement);replaceFirst(regex,replacement);matches(regex);split(regex);split(regex,limit)
String和其他類的轉(zhuǎn)換

1.String和包裝類之間的轉(zhuǎn)換
2.String和字符數(shù)組間(char[ ])的轉(zhuǎn)換

String s7 = "thanks";
      //String轉(zhuǎn)換為字符數(shù)組
      char[] chars = s7.toCharArray();
      for (int i = 0; i < chars.length; i++) {
          System.out.println(i);
      }

      char[] c = {'w','o','a'};
      //字符數(shù)組轉(zhuǎn)換為String
      String s8 = new String(c);
      System.out.println(s8);

3.String和字節(jié)數(shù)組(byte[ ])之間的轉(zhuǎn)換
(1)String-->byte[ ]編碼(看得懂--》看不懂二進(jìn)制數(shù)):調(diào)用String的getBytes()
(2)byte[ ]-->String解碼(看不懂二進(jìn)制數(shù)--》看得懂):調(diào)用String構(gòu)造器
解碼時(shí),要求解碼使用的字符集必須和編碼的方式一致,否則亂碼

//String轉(zhuǎn)換為字節(jié)數(shù)組(編碼)
       String s10 = "abc中國";
       byte[] bytes = s10.getBytes();//默認(rèn)編碼方式,此環(huán)境默認(rèn)utf-8,則編碼格式也為utf-8
       System.out.println(Arrays.toString(bytes));//[97, 98, 99, -28, -72, -83, -27, -101, -67]一個(gè)漢字由3個(gè)字節(jié)組成

       byte[] gbks = s10.getBytes("gbk");//使用gbk進(jìn)行編碼,需要拋出異常
       System.out.println(Arrays.toString(gbks));
       //字節(jié)數(shù)組轉(zhuǎn)為String(解碼)
       String s11 = new String(bytes);//使用默認(rèn)解碼方式解碼
       System.out.println(s11);

       String s12 = new String(gbks);//使用gbk方式解碼,出現(xiàn)亂碼,原因是使用gbk編碼,卻使用utf-8解碼
       System.out.println(s12);

       String s13 = new String(gbks,"gbk");//使用gbk編碼和解碼
       System.out.println(s13);

例題:

StringBuffer

常用方法:增、刪、改、查、插、長度、遍歷

 StringBuffer sb = new StringBuffer("abcdefg");
//        sb.append(1);
//        sb.append("2");
//        System.out.println(sb);//abcdefg12 用于字符串拼接;增

//        sb.delete(2,5);
//        System.out.println(sb);//abfg  刪除指定區(qū)間[  )位置數(shù)據(jù);刪

//        StringBuffer s = sb.replace(1, 3, "s");
//        System.out.println(s);//asdefg 把[start end)位置替換為str

//              StringBuffer insert = sb.insert(2, 3);
//        System.out.println(insert);//ab3cdefg 在指定位置插入數(shù)據(jù);插

//        StringBuffer reverse = sb.reverse();
//        System.out.println(reverse);//gfedcba 反轉(zhuǎn)順序

//        int i = sb.indexOf("1");
//        System.out.println(i);//-1 返回指定字符所在索引位置

//        String substring = sb.substring(1, 3);
//        System.out.println(substring);//bc 截取[ )的字符

//        char c = sb.charAt(2);
//        System.out.println(c);//c 獲得指定位置字符;查

        sb.setCharAt(2,'d');
        System.out.println(sb);//abddefg 將指定位置字符替換,并返回;改

//遍歷:for() + charAt()/toString()

StringBuilder

String、StringBuffer和StringBuilder的異同

String:不可變字符序列,底層使用char[]存儲
StringBuffer:可變字符序列,線程安全,效率低,底層使用char[]存儲
StringBuilder:可變字符序列,jdk5.0新增,線程不安全,效率高,底層使用char[]存儲
三者效率:StringBuilder > StringBuffer > String

源碼分析:

String str = new String();//char[] value = new char[0];
String str = new String("abc");//char[] value = new char[]{'a','b','c'};

StringBuffer sb1 = new StringBuffer ();//char[] value = new char[16];底層默認(rèn)創(chuàng)建了長度為16的char[]
System.out.println(sb1.length());//輸出結(jié)果為0,原因是雖然默認(rèn)創(chuàng)建16,但它創(chuàng)建時(shí)的實(shí)際長度為0
StringBuffer sb2 = new StringBuffer ("abc");//char[] value = new char[“abc”.length()+16];
//問題1.System.out.println(sb2.length());//3
//問題2.擴(kuò)容問題,若要添加的底層數(shù)據(jù)盛不下,則需要擴(kuò)容,默認(rèn)情況下,擴(kuò)容為原來容量的2倍加2,同時(shí)將原有數(shù)據(jù)又復(fù)制到新數(shù)組

JDK8之前日期時(shí)間API

1.System類中的currentTimeMillis(),返回當(dāng)前時(shí)間和1970年1月1日0時(shí)0分0秒之間以毫秒為單位的時(shí)間差,稱為時(shí)間戳(例如并發(fā)量不高時(shí)訂單號生成)
2.java.util.Date類和java.sql.Date類(同時(shí)是java.util.Date的子類)

(1)兩個(gè)構(gòu)造器的使用
構(gòu)造器一:Date()創(chuàng)建一個(gè)對應(yīng)當(dāng)前時(shí)間的Date對象
構(gòu)造器二:創(chuàng)建指定毫秒數(shù)的Date對象
(2)兩個(gè)方法的使用
toString()顯示當(dāng)前年月日時(shí)分秒
getTime()獲取當(dāng)前Date對象對應(yīng)的毫秒數(shù)(時(shí)間戳)
(3)java.sql.Date對應(yīng)數(shù)據(jù)庫中的日期類型變量
--》如何實(shí)例化
--》java.util.Date和java.sql.Date的相互轉(zhuǎn)化

java.util.Date
//構(gòu)造器一: 創(chuàng)建一個(gè)對應(yīng)當(dāng)前時(shí)間的Date對象
        Date date = new Date();
        System.out.println(date.getTime());//1586622502908L 返回當(dāng)前毫秒數(shù)
        System.out.println(date.toString());//Sun Apr 12 00:29:02 CST 2020

        //構(gòu)造器二:
        Date date2 = new Date(1586622542111L);
        System.out.println(date2.toString());//Sun Apr 12 00:29:02 CST 2020
java.sql.Date

java.sql.Date--》java.util.Date:多態(tài)
java.util.Date--》java.sql.Date:

 //創(chuàng)建java.sql.Date對象
        java.sql.Date date3 = new java.sql.Date(1586622542111L);
        System.out.println(date3);//2020-04-12

//將java.util.Date對象轉(zhuǎn)換為java.sql.Date
        //方式一:使用多態(tài)創(chuàng)建util的Date對象,再進(jìn)行強(qiáng)轉(zhuǎn)
        Date date4 = new java.sql.Date(1586622542111L);//多態(tài)
        System.out.println(date4.toString());//2020-04-12,但丟失了時(shí)分秒,原因是sql下沒有時(shí)分秒
        java.sql.Date date5 = (java.sql.Date) date4;//強(qiáng)轉(zhuǎn)
        System.out.println(date5);//2020-04-12
        //方式二:先創(chuàng)建util的Date對象,再創(chuàng)建Sql的Date對象的方式
        Date date6 = new Date();//new的父類
        java.sql.Date date7 = new java.sql.Date(date6.getTime());
        System.out.println(date7);//2020-04-12
        //錯誤方式
        Date d = new Date();//new的父類
        java.sql.Date d1 = (java.sql.Date) d;//強(qiáng)轉(zhuǎn)為子類,報(bào)錯java.util.Date cannot be cast to java.sql.Date
        System.out.println(d1);
例題
        String s = null;
        StringBuffer sb = new StringBuffer();
        sb.append(s);

        System.out.println(sb.length());//4
        System.out.println(sb.toString());//"null"

        StringBuffer sb1 = new StringBuffer(s);
        System.out.println(sb1);//java.lang.NullPointerException
3.java.text.SimpleDateFormat

(1)兩個(gè)操作
格式化:日期---》字符串:String format1 = sdf1.format(d1);
解析:字符串---》日期: Date date1 = sdf1.parse(str);
(2)SimpleDateFormat的實(shí)例化
使用默認(rèn)構(gòu)造器實(shí)例化:SimpleDateFormat sdf1 = new SimpleDateFormat();
使用帶參構(gòu)造器實(shí)例化: SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//1.使用默認(rèn)構(gòu)造器實(shí)例化SimpleDateFormat
        SimpleDateFormat sdf1 = new SimpleDateFormat();

        Date d1 = new Date();
        System.out.println(d1);//Sun Apr 12 10:32:13 CST 2020
        //日期---》字符串
        String format1 = sdf1.format(d1);
        System.out.println(format1);//20-4-12 上午10:31

        //字符串---》日期
        String str = "20-4-10 下午20:31";
        Date date1 = sdf1.parse(str);
        System.out.println(date1);//Sat Apr 11 08:31:00 CST 2020

        //2.使用帶參構(gòu)造器實(shí)例化SimpleDateFormat
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //日期---》字符串
        String format2 = sdf2.format(d1);
        System.out.println(format2);//2020-04-12 10:31:03
        //字符串---》日期,此時(shí)的參數(shù)格式需要和帶參構(gòu)造器sdf2對象格式一樣,否則報(bào)異常
        Date parse = sdf2.parse("2020-04-12 10:31:03");
        System.out.println(parse);

例題:將字符串"2020-02-03"轉(zhuǎn)換為java.sql.Date

 /*
        * 將字符串"2020-02-03"轉(zhuǎn)換為java.sql.Date
        * 1.將字符串轉(zhuǎn)化為util的Date
        * 2.將util的Date轉(zhuǎn)化為sql的Date
        * */
        String s = "2020-02-03";

        //1.將字符串轉(zhuǎn)化為util的Date

        //錯誤方式
        //SimpleDateFormat sdf = new SimpleDateFormat();
        // Date d = sdf.parse(s);//字符串---》日期(此種格式固定20-4-10 下午20:31)因此會出錯

        //正確方式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse(s);//轉(zhuǎn)換成util下的Date
        System.out.println(d);//Mon Feb 03 00:00:00 CST 2020

        //2。將util的Date轉(zhuǎn)為sql的Date
        java.sql.Date date = new java.sql.Date(d.getTime());
        System.out.println(date);

例題:"三天打漁兩天曬網(wǎng)" 1990-01-01開始,xxxx-xx-xx:打漁?曬網(wǎng)
思路:毫秒數(shù)之差/一天毫秒數(shù)+1
總天數(shù) % 5 == 1,2,3打漁;總天數(shù) % 5 == 4,0曬網(wǎng);

4.Calendar(抽象類)日歷類的使用

創(chuàng)建方式:

        //方式一:創(chuàng)建子類(GregorianCalendar)對象
        GregorianCalendar g = new GregorianCalendar();
        System.out.println("方式一"+g);
        //方式二:調(diào)用靜態(tài)方法
        Calendar calendar = Calendar.getInstance();
        System.out.println("方式二"+calendar);

常用方法:

        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//12當(dāng)前幾號
        //set()將Calendar.屬性的值設(shè)置為定義的值(改變原有calendar值)
        calendar.set(Calendar.DAY_OF_MONTH,6);
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//6  將12號設(shè)為6號
        //add()將Calendar.屬性的值加或減定義的值(改變原有calendar值)
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//5 將6號減1

        //getTime():日歷類--》Date
        System.out.println(calendar.getTime());//Sun Apr 05 11:59:53 CST 2020 獲得Date

        //setTime():Date--》日歷類
        Date d = new Date();//獲取Date
        calendar.setTime(d);//將Date--》日歷類
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//12  當(dāng)前定義Date幾號

注意:獲取月份:1月-->0 2月-->1 ........ 12月-->11
獲取星期:周日-->1 周一-->2 ...... 周六-->7

JDK8中新日期時(shí)間API(java.time和java.time.format下)不是1.8版本時(shí),可以導(dǎo)入Joda-Time的jar包

圖片.png

新API產(chǎn)生原因列舉兩:

        //問題之一:Date:年是從1900年開始,月從0開始,即有偏移,需要減去偏移量
        //問題二:Calendar日期時(shí)間可變,如 calendar.set(Calendar.DAY_OF_MONTH,6);

        Date d1 = new Date(2020,2,5);//(2020-2-5)
        Date d2 = new Date(2020-1900,2-1,5);//(2020-2-5)
        System.out.println(d1);//Fri Mar 05 00:00:00 CST 3920  (3920-3-5)
        System.out.println(d2);//Wed Feb 05 00:00:00 CST 2020  (2020-2-5)
LocalDateTime(使用頻率高)、LocalTime、LocalDate(使用類似于Calendar,方法獲取格式很相似)
        //兩種方式獲取時(shí)間,一:當(dāng)?shù)貢r(shí)間    二:自定義時(shí)間
        //now()獲取當(dāng)前時(shí)間
        LocalDateTime ldt = LocalDateTime.now();
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();

        System.out.println(ldt);//2020-04-12T12:39:14.022
        System.out.println(localDate);//2020-04-12
        System.out.println(localTime);//12:39:14.022
        //設(shè)置自定義時(shí)間
        LocalDateTime of = LocalDateTime.of(2015, 3, 5, 12, 24, 3);
        System.out.println(of);//2015-03-05T12:24:03

        //獲取
        System.out.println(ldt.getDayOfMonth());//12 獲取本月的幾號

        //設(shè)置,不改變原有值,即不可變性
        LocalDateTime ldt1 = ldt.withDayOfMonth(10);
        System.out.println(ldt);//2020-04-12T12:40:35.898
        System.out.println(ldt1);//2020-04-10T12:40:35.898

        //加減
        LocalDateTime localDateTime = ldt1.plusMonths(2);//向當(dāng)前時(shí)間加2月
        System.out.println(localDateTime);//2020-06-10T12:47:15.422
Instant瞬時(shí)(使用類似于java.util.Date)兩者都能獲得毫秒數(shù)
 //now()獲取本初子午線對應(yīng)的標(biāo)準(zhǔn)時(shí)間
        Instant instant = Instant.now();
        System.out.println(instant);//2020-04-12T05:03:40.537Z

        //atOffset(偏移參數(shù))添加偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2020-04-12T13:03:40.537+08:00

        //toEpochMilli()獲取自1970開始的毫秒數(shù)---》類似于Date類的getTime()
        long l = instant.toEpochMilli();
        System.out.println(l);//1586667820537

        //ofEpochMilli(給定毫秒數(shù))--》類似于Date(Long millis)
        Instant instant1 = Instant.ofEpochMilli(1586667739483L);
        System.out.println(instant1);//2020-04-12T05:02:19.483Z
格式化java.time.Format.DateTimeFormatter(使用類似于SimpleDateFormat)

方式一:預(yù)定義標(biāo)準(zhǔn)格式;
方式二:本地化相關(guān)的格式;
方式三:自定義格式

//方式一:預(yù)定義標(biāo)準(zhǔn)格式ISO_LOCAL_DATE_TIME 、ISO_LOCAL_TIME 、ISO_LOCAL_DATE
        DateTimeFormatter dtf= DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        //格式化:日期--》字符
        //1.創(chuàng)建需要格式化的對象
        LocalDateTime localDateTime = LocalDateTime.now();
        //2.格式化
        String format = dtf.format(localDateTime);

        System.out.println(localDateTime);//2020-04-12T13:27:19.652
        System.out.println(format);//2020-04-12T13:27:19.652

        //解析:字符串--》日期(預(yù)定義標(biāo)準(zhǔn)格式化時(shí),轉(zhuǎn)為日期,其參數(shù)格式必須和預(yù)定義格式一致)
        TemporalAccessor parse = dtf.parse("2020-04-12T13:27:19.652");
        System.out.println(parse);//{},ISO resolved to 2020-04-12T13:27:19.652

//方式二:本地化相關(guān)的格式
        //1.適用于LocalDateTime,參數(shù)如:FormatStyle.SHORT
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        //格式化
        String format1 = formatter.format(localDateTime);
        System.out.println(format1);//20-4-12 下午1:35

        //2.適用于LocalDate,參數(shù)和上述參數(shù)一致如:FormatStyle.FULL
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        LocalDate ld = LocalDate.now();
        //格式化
        String format2 = formatter1.format(ld);
        System.out.println(format2);//2020年4月12日 星期日

        //方式三:自定義格式 如:ofPattern()
        DateTimeFormatter dt = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format3 = dt.format(LocalDateTime.now());
        System.out.println(format3);//2020-04-12 01:57:26

        //解析
        TemporalAccessor parse1 = dt.parse("2020-04-12 01:57:26");
        System.out.println(parse1);//{SecondOfMinute=26, HourOfAmPm=1, MilliOfSecond=0, NanoOfSecond=0, MicroOfSecond=0, MinuteOfHour=57},ISO resolved to 2020-04-12

對象排序:兩種接口

自然排序:java.lang.Comparable

使用舉例:
1.像String、包裝類等實(shí)現(xiàn)了Comparable接口,重寫了Comparable(obj)方法,給出了比較兩個(gè)對象的大小,默認(rèn)進(jìn)行了從小到大的排序

String[] s = new String[]{"aa","bb","ff","cc","dd"};
        Arrays.sort(s);
//Arrays.toString(s):將s類型的數(shù)組以字符串格式返回
        System.out.println(Arrays.toString(s));//[aa, bb, cc, dd, ff]

2.重寫CompareTo(obj)規(guī)則:
當(dāng)前對象this大于形參對象obj,返回正整數(shù);當(dāng)前對象this小于形參對象,返回負(fù)整數(shù);兩者相等,返回0
3.對于自定義類來說,若需要排序,則讓該類實(shí)現(xiàn)Comparable接口,重寫CompareTo(obj)方法,在該方法中指明如何排序

public class Person implements Comparable{
    private String name;
    private int age;
 //此方法中比較對象,對象按照一定的屬性進(jìn)行比較
    @Override
    public int compareTo(Object o) {
        //方式一:
        //按照name屬性進(jìn)行比較
        if(o instanceof Person){//instanceof測試該對象是否為一個(gè)類的實(shí)例
            Person p = (Person) o;//將該對象向上轉(zhuǎn)型為父類的實(shí)例,即轉(zhuǎn)為同一類對象進(jìn)行比較
            if(this.age > p.age){//按照從小到大排序
                return 1;
            }else if(this.age < p.age){//按照從大到小排序
                return -1;
            }else{
//                return 0;//只按照age排序
                return this.name.compareTo(p.name);//按照age排序的同時(shí)按照name排序
            }
//            //方式二
//            return -Integer.compare(this.age,p.age);//按照從大到小排序
        }

        throw new RuntimeException("傳入數(shù)據(jù)類型不一致異常");
    }
}

//對人進(jìn)行排序
        Person[] p = new Person[4];
        p[0] = new Person("wangqu",24);
        p[1] = new Person("zhangsan",14);
        p[2] = new Person("xiaohong",12);
        p[3] = new Person("angqu",24);

        Arrays.sort(p);//在未對Person實(shí)現(xiàn)Comparable接口時(shí),異常cannot be cast to java.lang.Comparable
        System.out.println(Arrays.toString(p));

定制排序:java.util.Comparator

重寫Compare(Object o1,Object o2)方法,比較o1和o2大小

 String[] s = new String[]{"aa","bb","ff","cc","dd"};
        Arrays.sort(s, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof String && o2 instanceof String ){//判斷其左邊對象是否為其右邊類的實(shí)例
                    String s1 = (String) o1;
                    String s2 = (String) o2;

                    return -s1.compareTo(s2);
                }
                throw new RuntimeException("返回值類型錯誤");
            }
        });
        System.out.println(Arrays.toString(s));

說明:Comparable接口和Comparator接口的對比
Comparable接口方式一旦指定,可以保證Comparable接口實(shí)現(xiàn)類的對象在任何位置都可以比較大小
Comparator接口屬于臨時(shí)性比較

System

System.exit(0);表示正常退出程序;負(fù)數(shù)表示異常退出
System.gc();要求系統(tǒng)進(jìn)行垃圾回收,但不一定立刻回收
System.getProperty(String key);獲取系統(tǒng)中屬性名為key的值

Math

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容