1. 程式人生 > 其它 >Java學習筆記112——正則表示式

Java學習筆記112——正則表示式

正則表示式

package com.shujia.java.test;
​
/*
  校驗QQ號是否合法
  1、必須是5-10位的
  2、0不能作為QQ號的開頭
​
  3、必須都是數字
​
  檢查輸入的郵箱是否合法
    1、名稱由數字字母特殊符號組成
    2、長度5-10
    3、含有@符號
    4、....
 */
public class RegularDemo1 {
  public static void main(String[] args) {
    String s = "023w2341232";
    System.out.println(checkQQ(s));
​
   }
​
  public static boolean checkQQ(String qq){
    boolean flag = false;
​
    //必須是5-10位的
    if(qq.length() >=5 && qq.length()<=10){
      //保證不是0開頭
      if(!qq.startsWith("0")){
        flag = true;
​
        //必須都是數字
        char[] chars = qq.toCharArray();
        for (char aChar : chars) {
          if(!Character.isDigit(aChar)){
            flag = false;
            break;
           }
         }
​
       }
​
     }
​
​
    return flag;
   }
​
  public static boolean checkQQByRegular(String s){
​
    //使用正則表示式可以很容易地完成字串地查詢、匹配替換地工作
    //正則表示式
    String regex = "[1-9][0-9][4,9]";
    return s.matches(regex);
​
   }
}
​

學習正則表示式的目的:通過正則表示式處理了字串複雜的查詢/替換/匹配/分割工作

1001,xiaohu,18,14

json, xml, html

正則表示式是一個獨立於java的技術,不依附於java,它可以在java中使用,也可以在python/JS等中去使用

正則表示式的概述

概念:使用單個字串來描述或者描述/匹配一系列符合某個語法規則的字串

使用步驟:

1、通過大量的字串你找規律定義規則

2、使用這種規則去匹配新的字串

3、匹配成功做出相應的操作

[email protected]

正則表示式的語法規則

1、原義字元

字元本身就是一個正則

a b c \t \n \r \f
public class RegularDemo2 {
  public static void main(String[] args) {
    //原義字元
    String regex = "a";
    String str = "ab123241dasdasw&;123.";
    System.out.println(str.replaceAll(regex,"X"));
​
   }
}

輸出結果:

Xb123241dXsdXsw&;123.

2、元字元

字元 描述
\ 將下一個字元標記為一個特殊字元、或一個原義字元、或一個 向後引用、或一個八進位制轉義符。例如,'n' 匹配字元 "n"。'\n' 匹配一個換行符。序列 '\' 匹配 "" 而 "(" 則匹配 "("。
^ 匹配輸入字串的開始位置。如果設定了 RegExp 物件的 Multiline 屬性,^ 也匹配 '\n' 或 '\r' 之後的位置。
$ 匹配輸入字串的結束位置。如果設定了RegExp 物件的 Multiline 屬性,$ 也匹配 '\n' 或 '\r' 之前的位置。
*
匹配前面的子表示式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。* 等價於{0,}。
+ 匹配前面的子表示式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等價於 {1,}。
? 匹配前面的子表示式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 。? 等價於 {0,1}。
{n} n 是一個非負整數。匹配確定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的兩個 o。
{n,} n 是一個非負整數。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等價於 'o+'。'o{0,}' 則等價於 'o*'。
{n,m} m 和 n 均為非負整數,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 將匹配 "fooooood" 中的前三個 o。'o{0,1}' 等價於 'o?'。請注意在逗號和兩個數之間不能有空格。
? 當該字元緊跟在任何一個其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 後面時,匹配模式是非貪婪的。非貪婪模式儘可能少的匹配所搜尋的字串,而預設的貪婪模式則儘可能多的匹配所搜尋的字串。例如,對於字串 "oooo",'o+?' 將匹配單個 "o",而 'o+' 將匹配所有 'o'。
. 匹配除換行符(\n、\r)之外的任何單個字元。要匹配包括 '\n' 在內的任何字元,請使用像"(.|\n)"的模式。
(pattern) 匹配 pattern 並獲取這一匹配。所獲取的匹配可以從產生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中則使用 $0…$9 屬性。要匹配圓括號字元,請使用 '(' 或 ')'。
(?:pattern) 匹配 pattern 但不獲取匹配結果,也就是說這是一個非獲取匹配,不進行儲存供以後使用。這在使用 "或" 字元 (|) 來組合一個模式的各個部分是很有用。例如, 'industr(?:y|ies) 就是一個比 'industry|industries' 更簡略的表示式。
(?=pattern) 正向肯定預查(look ahead positive assert),在任何匹配pattern的字串開始處匹配查詢字串。這是一個非獲取匹配,也就是說,該匹配不需要獲取供以後使用。例如,"Windows(?=95|98|NT|2000)"能匹配"Windows2000"中的"Windows",但不能匹配"Windows3.1"中的"Windows"。預查不消耗字元,也就是說,在一個匹配發生後,在最後一次匹配之後立即開始下一次匹配的搜尋,而不是從包含預查的字元之後開始。
(?!pattern) 正向否定預查(negative assert),在任何不匹配pattern的字串開始處匹配查詢字串。這是一個非獲取匹配,也就是說,該匹配不需要獲取供以後使用。例如"Windows(?!95|98|NT|2000)"能匹配"Windows3.1"中的"Windows",但不能匹配"Windows2000"中的"Windows"。預查不消耗字元,也就是說,在一個匹配發生後,在最後一次匹配之後立即開始下一次匹配的搜尋,而不是從包含預查的字元之後開始。
(?<=pattern) 反向(look behind)肯定預查,與正向肯定預查類似,只是方向相反。例如,"(?<=95|98|NT|2000)Windows"能匹配"2000Windows"中的"Windows",但不能匹配"3.1Windows"中的"Windows"。
(?<!pattern) 反向否定預查,與正向否定預查類似,只是方向相反。例如"(?<!95|98|NT|2000)Windows"能匹配"3.1Windows"中的"Windows",但不能匹配"2000Windows"中的"Windows"。
x|y 匹配 x 或 y。例如,'z|food' 能匹配 "z" 或 "food"。'(z|f)ood' 則匹配 "zood" 或 "food"。
[xyz] 字元集合。匹配所包含的任意一個字元。例如, '[abc]' 可以匹配 "plain" 中的 'a'。
[^xyz] 負值字元集合。匹配未包含的任意字元。例如, 'abc' 可以匹配 "plain" 中的'p'、'l'、'i'、'n'。
[a-z] 字元範圍。匹配指定範圍內的任意字元。例如,'[a-z]' 可以匹配 'a' 到 'z' 範圍內的任意小寫字母字元。
[^a-z] 負值字元範圍。匹配任何不在指定範圍內的任意字元。例如,'a-z' 可以匹配任何不在 'a' 到 'z' 範圍內的任意字元。
\b 匹配一個單詞邊界,也就是指單詞和空格間的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\B 匹配非單詞邊界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。
\cx 匹配由 x 指明的控制字元。例如, \cM 匹配一個 Control-M 或回車符。x 的值必須為 A-Z 或 a-z 之一。否則,將 c 視為一個原義的 'c' 字元。
\d 匹配一個數字字元。等價於 [0-9]。
\D 匹配一個非數字字元。等價於 0-9
\f 匹配一個換頁符。等價於 \x0c 和 \cL。
\n 匹配一個換行符。等價於 \x0a 和 \cJ。
\r 匹配一個回車符。等價於 \x0d 和 \cM。
\s 匹配任何空白字元,包括空格、製表符、換頁符等等。等價於 [ \f\n\r\t\v]。
\S 匹配任何非空白字元。等價於 \f\n\r\t\v
\t 匹配一個製表符。等價於 \x09 和 \cI。
\v 匹配一個垂直製表符。等價於 \x0b 和 \cK。
\w 匹配字母、數字、下劃線。等價於'[A-Za-z0-9_]'。
\W 匹配非字母、數字、下劃線。等價於 'A-Za-z0-9_'。
\xn 匹配 n,其中 n 為十六進位制轉義值。十六進位制轉義值必須為確定的兩個數字長。例如,'\x41' 匹配 "A"。'\x041' 則等價於 '\x04' & "1"。正則表示式中可以使用 ASCII 編碼。
\num 匹配 num,其中 num 是一個正整數。對所獲取的匹配的引用。例如,'(.)\1' 匹配兩個連續的相同字元。
\n 標識一個八進位制轉義值或一個向後引用。如果 \n 之前至少 n 個獲取的子表示式,則 n 為向後引用。否則,如果 n 為八進位制數字 (0-7),則 n 為一個八進位制轉義值。
\nm 標識一個八進位制轉義值或一個向後引用。如果 \nm 之前至少有 nm 個獲得子表示式,則 nm 為向後引用。如果 \nm 之前至少有 n 個獲取,則 n 為一個後跟文字 m 的向後引用。如果前面的條件都不滿足,若 n 和 m 均為八進位制數字 (0-7),則 \nm 將匹配八進位制轉義值 nm。
\nml 如果 n 為八進位制數字 (0-3),且 m 和 l 均為八進位制數字 (0-7),則匹配八進位制轉義值 nml。
\un 匹配 n,其中 n 是一個用四個十六進位制數字表示的 Unicode 字元。例如, \u00A9 匹配版權符號 (?)。

字元類:
package com.shujia.wyh.day21;
​
/*
  元字元:
    字元類
 */
public class RegularDemo3 {
  public static void main(String[] args) {
    //表示格式:[]
    //[]表示將字元進行歸類,可以匹配出現在中括號中的任意一個字元
    //只要被匹配的字串中存在a,b,2中任何一個,都會被替換
    String regex = "[ab2]";
    String s = "ab123241dasdasw&;123.";
    System.out.println(s.replaceAll(regex, "_"));
​
    //^出現在中括號中,代表的意思式取反,對不是ab2的字元進行匹配
    regex = "[^ab2]";
    System.out.println(s.replaceAll(regex, "+"));
​
​
   }
}
​

輸出結果:

__1_3_41d_sd_sw&;1_3.
ab+2+2+++a++a+++++2++

範圍類:

其實實在字元類的基礎之上增加了範圍

package com.shujia.wyh.day21;
​
/*
    元字元:
      範圍類 基於字元類的基礎之上增加的內容
 */
public class RegularDemo4 {
  public static void main(String[] args) {
    String regex = "[ab]";
    String s = "abcdefghijklmnBV1232QWE41dasdasw&;123.";
    System.out.println("匹配之前:\n" + s);
    System.out.println("====================================");
    System.out.println(s.replaceAll(regex, "_"));
​
    //[a-z]表示的是匹配a到z中的任意一個小寫字母
    regex = "[a-z]";
    System.out.println(s.replaceAll(regex, "_"));
​
    //[A-Z]表示的是匹配a到z中的任意一個大寫字母
    regex = "[A-Z]";
    System.out.println(s.replaceAll(regex, "+"));
​
    //既想匹配小寫又想匹配大寫
    regex = "[a-zA-Z]";
    System.out.println();
    System.out.println(s.replaceAll(regex, "#"));
​
    //想匹配數字咋辦
    regex = "[0-9]";
    System.out.println(s.replaceAll(regex, "_"));
​
    //既想匹配小寫又想匹配大寫和數字
    regex = "[a-zA-Z0-9&;.]";
    System.out.println(s.replaceAll(regex, "_"));
​
​
   }
}
​

輸出結果:

匹配之前:
abcdefghijklmnBV1232QWE41dasdasw&;123.
====================================
__cdefghijklmnBV1232QWE41d_sd_sw&;123.
______________BV1232QWE41_______&;123.
abcdefghijklmn++1232+++41dasdasw&;123.
​
################1232###41#######&;123.
abcdefghijklmnBV____QWE__dasdasw&;___.
______________________________________

預定義類:

我們在上面的範圍類的情況下我們在實際開發中可能會遇到一些常見的需求,比如:判斷是否是數字、小寫字母、大寫字母等這些情況,對應的範圍類的正則會比較長,所以在正則表示式中會給我們預定一些有特殊含義的表示式,正則表示式把我們常見的整理了一下

\d == [0-9] 數字
\D == [^0-9] 非數字
空白字元:[\t\n\x0B\f\r] == \s
[^ \t\n\x0B\f\r] == \S
\w == [a-zA-Z0-9]
\W == [^a-zA-Z0-9]
. 任何字元(與行結束符可能匹配也可能不匹配)
package com.shujia.wyh.day21;
​
/*
    \d == [0-9] 數字
    \D == [^0-9] 非數字
    空白字元:[\t\n\x0B\f\r] == \s
    [^ \t\n\x0B\f\r] == \S
    \w == [a-zA-Z0-9]
    \W == [^a-zA-Z0-9]
    . 任何字元(與行結束符可能匹配也可能不匹配)
 */
public class RegularDemo5 {
  public static void main(String[] args) {
    String regex = "[0-9]";
    String s = "abcdefghijklmnB V1232Q WE 41dasdasw&;123.";
    System.out.println("匹配之前:\n" + s);
    System.out.println("====================================");
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\d"; //[0-9] 匹配所有的數字
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\D"; //匹配所有非數字的字元
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\s"; //匹配所有空白字元
    System.out.println(s.replaceAll(regex, "!"));
​
    regex = "\\S"; //匹配所有非空白字元
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\w"; //匹配所有的大小寫字母和數字
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\W"; //匹配所有的非大小寫字母和數字
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "."; //匹配任何字元
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\.";
    System.out.println(s.replaceAll(regex, "_"));
   }
}
​

輸出結果:

匹配之前:
abcdefghijklmnB V1232Q WE 41dasdasw&;123.
====================================
abcdefghijklmnB V____Q WE __dasdasw&;___.
abcdefghijklmnB V____Q WE __dasdasw&;___.
_________________1232_____41_________123_
abcdefghijklmnB!V1232Q!WE!41dasdasw&;123.
_______________ ______ __ _______________
_______________ ______ __ _________&;___.
abcdefghijklmnB_V1232Q_WE_41dasdasw__123_
_________________________________________
abcdefghijklmnB V1232Q WE 41dasdasw&;123_

邊界字元:
^:以xxx開頭
$:以xxx結尾
\b:單詞邊界
\B:非單詞邊界
package com.shujia.wyh.day21;
​
/*
  元字元
    邊界字元
      ^:以xxx開頭
      $:以xxx結尾
      \b:單詞邊界
      \B:非單詞邊界
 */
public class RegularDemo6 {
  public static void main(String[] args) {
    //在沒有中括號的時候,^代表的是以什麼開頭
    String regex = "^ac";
    String s = "abcdefg";
    System.out.println("匹配之前:\n" + s);
    System.out.println("====================================");
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "fg$";
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\b";
    s = "Hello World 888 1 2 & ; 0 a b c d";
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "\\B";
    System.out.println(s.replaceAll(regex, "_"));
​
   }
}
​

輸出結果:

匹配之前:
abcdefg
====================================
abcdefg
abcde_
_Hello_ _World_ _888_ _1_ _2_ & ; _0_ _a_ _b_ _c_ _d_
H_e_l_l_o W_o_r_l_d 8_8_8 1 2 _&_ _;_ 0 a b c d

量詞:
?:出現0次或者1次
+:出現1次或者多次
*:出現任意次
{n}:出現正好n次
{n,m}:出現n-m次
{n,}出現至少n次
package com.shujia.wyh.day21;
​
/*
  元字元
    量詞分類:
      ?:出現0次或者1次
      +:出現1次或者多次
      *:出現任意次
      {n}:出現正好n次
      {n,m}:出現n-m次
      {n,}出現至少n次
 */
public class RegularDemo7 {
  public static void main(String[] args) {
    //匹配以a開頭的0次或者1次
//     String regex = "^a?";
    String regex = "^b?";
    String s = "aaaaabcdefaaaaaag";
    System.out.println("匹配之前:\n" + s);
    System.out.println("====================================");
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "^a+";
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "^b+";
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "^a*";
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "^b*";
    System.out.println(s.replaceAll(regex, "_"));
​
    //{n}:出現正好n次
    //匹配a連續出現了6次
    //aaaaabcdefaaaaaag
    regex = "a{6}";
//     s = "aaaaabcdefaaaaaag";
    System.out.println(s.replaceAll(regex, "_"));
​
    regex = "a{3}";
    System.out.println(s.replaceAll(regex, "_"));
​
    //{n,m}:出現n-m次
    regex = "^a{3,4}";
    System.out.println(s.replaceAll(regex, "_"));
​
    //{n,}出現至少n次
    regex = "a{6,}";
    System.out.println(s.replaceAll(regex, "_"));
​
   }
}
​

輸出結果:

匹配之前:
aaaaabcdefaaaaaag
====================================
_aaaaabcdefaaaaaag
_bcdefaaaaaag
aaaaabcdefaaaaaag
_bcdefaaaaaag
_aaaaabcdefaaaaaag
aaaaabcdef_g
_aabcdef__g
_abcdefaaaaaag
aaaaabcdef_g

分組:

分組符號為 "( )"

package com.shujia.wyh.day21;
​
/*
    元字元:
      分組
        用小括號表示
 */
public class RegularDemo8 {
  public static void main(String[] args) {
    //表示匹配的是ab加上n個c
    String regex = "abc{1,2}";
    String s = "abccccABC123123baCBAabcccccABCabcabcabc123";
    System.out.println("匹配之前:\n" + s);
    System.out.println("====================================");
    System.out.println(s.replaceAll(regex, "_"));
​
    //表示匹配abc這個整體出現了1次到2次
    regex = "(abc){1,2}";
    System.out.println(s.replaceAll(regex, "+"));
​
    regex = "ABC(123|abc){1,}";
    System.out.println(s.replaceAll(regex, "+"));
​
    System.out.println(s.matches(regex)); //false
​
​
   }
}
​

輸出結果:

匹配之前:
abccccABC123123baCBAabcccccABCabcabcabc123
====================================
_ccABC123123baCBA_cccABC___123
+cccABC123123baCBA+ccccABC++123
abcccc+baCBAabccccc+
false

反向引用:
package com.shujia.wyh.day21;
​
/*
  元字元
    反向引用
    使用$引用對應組號的內容,每一個匹配的內容組號從1開始編號
​
 */
public class RegularDemo9 {
  public static void main(String[] args) {
    //2018-04-27 ---> 04/27/2018
    String regex = "(\\d{4})-(\\d{2})-(\\d{2})";
    String str = "2018-04-27 2021-12-17";
    System.out.println(str.replaceAll(regex, "$2/$3/$1"));
​
    //2018-04-27 ---> 04/27/2018
    //分組中如果不想要生成分組編號,可以通過?:來實現
    regex = "(\\d{4})-(?:\\d{2})-(\\d{2})";
    str = "2018-04-27 2021-12-17";
    System.out.println(str.replaceAll(regex, "$2/$1"));
   }
}
​

輸出結果:

04/27/2018 12/17/2021
27/2018 17/2021

正則表示式在java中的應用

在java中是如何使用正則表示式來實現相關操作的?

1、字串的查詢操作:Pattern和Matcher

2、字串匹配操作:可以用該字串的matchers方法

3、字串的替換操作:字串的replaceAll()和replaceFirst()方法

4、字串的分割:字串的split()方法

package com.shujia.java.day27.regulardemos;
​
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
​
/*
  1、字串的查詢操作:Pattern和Matcher
​
2、字串匹配操作:可以勇敢字串的matchers方法
​
3、字串的替換操作:字串的replaceAll()和replaceFirst()方法
​
4、字串的分割:字串的split()方法
 */
public class ReDemo10 {
  public static void main(String[] args) {
    String regex = "\\w{3,}";
    String str = "abcd123";
​
    System.out.println(str.matches(regex));
​
    regex = "[a-z]{2,}";
    str = "abc efgsd hello111";
    System.out.println(str.replaceAll(regex,"X"));
    System.out.println(str.replaceFirst(regex,"X"));
​
    str = "abc,sdf 123ab sa123bds & ";
    String[] split = str.split(",");
    System.out.println(Arrays.toString(split));
​
    regex = "[as1]";
    String[] split2 = str.split(regex);
    System.out.println(Arrays.toString(split2));
​
    //Pattern API
​
    regex = "\\w{3,7}";
    Pattern compile = Pattern.compile(regex);
    Matcher matcher = compile.matcher("abcd123aaaa112321dddd333");
//     System.out.println(matcher.matches());
    System.out.println(matcher.find());
    System.out.println(matcher.end());
    System.out.println(matcher.group());
​
    System.out.println(matcher.find());
    System.out.println(matcher.end());
    System.out.println(matcher.group());
   }
​
}
​

正則表示式驗證的網站:

https://regexper.com/

正則表示式練習

一、治療口吃。

將字串“我我我我我我我..........我.......要要要要要..................要要要要...學習習習習.......習習習習習習習習程式設計程程程程程.......程程程程程程程程程”變成“我要學習程式設計”

分析:先將....去掉:使用"\.+"模式,再將疊詞替換成一個:使用"(.)\1+"模式。

package p02.Exercise;
​
public class Demo01 {
  public static void main(String args[])
   {
    String str="我我我我我我我..........我.......要要要要要..................要要要要...學習習習習.......習習習習習習習習程式設計程程程程程.......程程程程程程程程程";
    //1.先去掉.
    String regex="\\.+";
    str=str.replaceAll(regex, "");
//     System.out.println(str);
    //2.合併疊詞。
    regex="(.)\\1+";
    str=str.replaceAll(regex, "$1");
    System.out.println(str);
   }
}

2、列舉型別

類的物件只有有限個,確定的,我們就可以稱之為列舉

星期:Monday(星期一).....Sunday(星期天)

性別:Man(男),Woman(女)

季節:Spring(春天)...winter(冬天)

就職狀態。。。

當需要定義一組常量的時候,強烈建議使用列舉

JDK1.5之前:自定義列舉

package com.shujia.java.day27.regulardemos;
​
/*
  列舉類:
    JDK1.5之前:自定義列舉
    JDK1.5之後:通過關鍵字enum定義列舉類
 */
public class EnumDemo1 {
  public static void main(String[] args) {
    Season spring = Season.SPRING;
    System.out.println(spring);
   }
}
​
/**
 *  自定義一個季節列舉類
 */
class Season{
  //2、建立Season的屬性,常量處理
  private final String SEASON_NAME;
  private final String SEASON_DESC;
​
​
  //1、要保證類的物件的個數是有限的
  //那麼我們必須要私有構造方法
  private Season(String SEASON_NAME,String SEASON_DESC){
    this.SEASON_NAME = SEASON_NAME;
    this.SEASON_DESC = SEASON_DESC;
   }
​
  //3、提供公共的靜態的方法給外界獲取列舉類的多個物件
  public static final Season SPRING = new Season("春天", "萬物復甦");
  public static final Season SUMMER = new Season("夏天", "萬物復甦2");
  public static final Season AUTUMN = new Season("秋天", "萬物復甦3");
  public static final Season WINTER = new Season("冬天", "萬物復甦4");
​
  //4、提供SEASON_NAME和SEASON_DESC的get方法
  public String getSEASON_NAME() {
    return SEASON_NAME;
   }
​
  public String getSEASON_DESC() {
    return SEASON_DESC;
   }
​
  //5、重寫toString()
​
  @Override
  public String toString() {
    return "Season{" +
        "SEASON_NAME='" + SEASON_NAME + '\'' +
        ", SEASON_DESC='" + SEASON_DESC + '\'' +
        '}';
   }
}
​

JDK1.5之後:通過關鍵字enum定義列舉類

package com.shujia.java.day27.regulardemos;
​
/*
  列舉類:
    JDK1.5之前:自定義列舉
    JDK1.5之後:通過關鍵字enum定義列舉類
 */
public class EnumDemo2 {
  public static void main(String[] args) {
    Season2 spring = Season2.SPRING;
    System.out.println(spring);
    System.out.println(Season2.class.getSuperclass());
   }
}
​
/**
 *  自定義一個季節列舉類
 */
enum Season2{
​
  //3、列舉有的有限個物件,物件之間通過逗號連線,最後一個分號結尾
  //列舉相關的放在頭部
  SPRING("春天", "萬物復甦"),
  SUMMER("夏天", "萬物復甦2"),
  AUTUMN("秋天", "萬物復甦3"),
  WINTER("冬天", "萬物復甦4");
​
  //2、建立Season2的屬性,常量處理
  private final String SEASON_NAME;
  private final String SEASON_DESC;
​
​
  //1、要保證類的物件的個數是有限的
  //那麼我們必須要私有構造方法
  private Season2(String SEASON_NAME,String SEASON_DESC){
    this.SEASON_NAME = SEASON_NAME;
    this.SEASON_DESC = SEASON_DESC;
   }
​
​
  //4、提供SEASON_NAME和SEASON_DESC的get方法
  public String getSEASON_NAME() {
    return SEASON_NAME;
   }
​
  public String getSEASON_DESC() {
    return SEASON_DESC;
   }
​
  //5、重寫toString()
​
//   @Override
//   public String toString() {
//     return "Season{" +
//         "SEASON_NAME='" + SEASON_NAME + '\'' +
//         ", SEASON_DESC='" + SEASON_DESC + '\'' +
//         '}';
//   }
}
​

列舉類可以實現介面

1、直接在列舉類實現介面中的抽象方法

2、在每個列舉物件中實現