正则表达式
package com.wyh.day16; /* 需求:验证QQ号是否符合规定 1、必须是5-10位 2、0不能作为QQ号的开头 3、必须都是数字 */ public class RegularDemo1 { public static void main(String[] args) { String s = "1164517877"; //写一个方法去验证这是不是合法的qq // System.out.println(checkQQ(s)); //感受一下正则处理这样的情况 System.out.println(checkQQ2(s)); } //正则处理 public static boolean checkQQ2(String qq){ //写一个正则表达式 String regex = "[1-9][0-9]{4,9}"; return qq.matches(regex); } /** * 返回值类型:boolean * 参数列表:String */ public static boolean checkQQ(String qq){ boolean flag = false; //1、必须是5-10位 if(qq.length() >= 5 && qq.length()<=10){ //2、0不能作为QQ号的开头 if(!qq.startsWith("0")){ flag = true; //3、必须都是数字 char[] chars = qq.toCharArray(); for(int i=0;i<chars.length;i++){ //public static boolean isDigit(char ch)确定指定的字符是否是数字。 if(!Character.isDigit(chars[i])){ // return false; flag = false; } } } } // return true; return flag; } }
运行结果
true
学习正则表达式的目的:通过正则表达式处理字符串复杂的查找/替换/匹配/分割工作
1001,xiaohu,18
正则表达式是独立于java的技术,不依附于java,但是它可以在java中使用,也可以在python/js等中使用
正则表达式的概述
正则表达式的概念:使用单个字符串来描述或者匹配一系列符合某种语法规则的字符串
正则表达式的使用步骤:
1、通过大量的字符串寻找规律,得出定义规则
2、使用这种规则去匹配新的字符串
3、匹配成功做出相应的操作
正则表达式的基本语法
1、原义字符
字符本身就是一个正则
/* 正则表达式: 1、原义字符 */ public class RedularDemo2 { public static void main(String[] args) { String str = "ab123342asdasqwe&;123."; //String类中有一个方法是替换功能,替换所有符合规则的字符 //public String replaceAll(String regex,String replacement) // 用给定的替换替换与给定的regular expression匹配的此字符串的每个子字符串。 String regex = "\\."; System.out.println(str.replaceAll(regex,"_")); regex = "b"; System.out.println(str.replaceAll(regex,"_")); } }
输出:
ab123342asdasqwe&;123_ a_123342asdasqwe&;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 匹配版权符号 (?)。 |
2.1 字符类
[]
/* 元字符: 字符类 */ public class RegularDemo3 { public static void main(String[] args) { String s = "ab123342asdasqwe&;123."; //表示格式:[] //[]表示的是将字符进行归类,可以匹配出现在中括号中的任意一个字符 //只要被匹配的字符串中存在a,b,2中任何一个,都会被匹配到 String regex = "[ab2]"; System.out.println(s.replaceAll(regex,"_")); //需求:除了ab2以外,都要被匹配替换 //^出现中括号代表的意思是取反,对不是ab2的字符进行匹配 regex = "[^ab2]"; System.out.println(s.replaceAll(regex,"_")); } }
输出结果:
__1_334__sd_sqwe&;1_3. ab_2___2a__a_______2__
2.2 范围类
其实就是在字符类的基础上增加了一个范围
package com.wyh.day16; /* 元字符: 2.1 范围类 其实就是在字符类的基础上增加了一个范围 */ public class RegularDemo4 { public static void main(String[] args) { String regex = "[ab]"; String s = "abcdefghijklmnABCDTW1234DWFadqwr&;123=."; System.out.println("匹配之前:" + 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]"; regex = "[A-z]"; System.out.println(s.replaceAll(regex, "_")); //现在想匹配数字怎么办? regex = "[0-9]"; System.out.println(s.replaceAll(regex, "_")); //又想匹配数字又想匹配大小写字母 regex = "[0-z&.]"; System.out.println(s.replaceAll(regex, "_")); } }
输出结果:
匹配之前:abcdefghijklmnABCDTW1234DWFadqwr&;123=. ========================================= __cdefghijklmnABCDTW1234DWF_dqwr&;123=. ______________ABCDTW1234DWF_____&;123=. abcdefghijklmn______1234___adqwr&;123=. ____________________1234________&;123=. abcdefghijklmnABCDTW____DWFadqwr&;___=. _______________________________________
2.3 预定义类:
我们在上一个案例的时候,使用范围类的情况下,在实际开发中可能会遇见一些常见的需求,比如:判断是否是数字、小写字母、大写字母等这些情况,对应的正则表达式就会比较长,所以在正则表达式中给我们预定一些有特殊含义的表达式,正则表达式替我们整理了一些
\d == [0-9]数字 \D == [^0-9]非数字 \s == [\r\n\f\r]空白字符 \S == [^\r\n\f\r]空白字符 \w == [a-zA-Z0-9] \W == [^a-zA-Z0-9] . == 代表任意字符
/* 元字符: 2.3 预定义类: 我们在上一个案例的时候,使用范围类的情况下,在实际开发中可能会遇见一些常见的需求, 比如:判断是否是数字、小写字母、大写字母等这些情况,对应的正则表达式就会比较长, 所以在正则表达式中给我们预定一些有特殊含义的表达式,正则表达式替我们整理了一些 \d == [0-9]数字 c == [^0-9]非数字 \s == [\r\n\f\r]空白字符 \S == [^\r\n\f\r]空白字符 \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 = "abcde fghijklmn ABCDTW12.....34D WFadq r&;1!!!!23=."; System.out.println("匹配之前:" + 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, "_")); } }
输出结果:
匹配之前:abcde fghijklmn ABCDTW12.....34D WFadq r&;1!!!!23=. ========================================= abcde fghijklmn ABCDTW__.....__D WFadq r&;_!!!!__=. abcde fghijklmn ABCDTW__.....__D WFadq r&;_!!!!__=. ______________________12_____34___________1____23__ abcde_fghijklmn_ABCDTW12.....34D_WFadq_r&;1!!!!23=. _____ _________ ________________ _____ ____________ _____ _________ ________.....___ _____ _&;_!!!!__=. abcde_fghijklmn_ABCDTW12_____34D_WFadq_r__1____23__ ___________________________________________________ abcde fghijklmn ABCDTW12_____34D WFadq r&;1!!!!23=_ Process finished with exit code 0
2.4 边界类字符
^: 不在中括号中出现,表示的是以xxx开头 $: 以xxx结尾 \b: 单词边界 \B: 非单词边界
/* 元字符: 边界类: ^: 不在中括号中出现,表示的是以xxx开头 $: 以xxx结尾 \b: 单词边界 \B: 非单词边界 */ public class RegularDemo6 { public static void main(String[] args) { //在没有中括号的时候使用^,^表示的是以xxx开头,这里表示的是以ac开头 String regex = "^abc"; String s = "abcdefg"; System.out.println("匹配之前:" + s); System.out.println("========================================="); System.out.println(s.replaceAll(regex, "_")); regex = "fg$"; System.out.println(s.replaceAll(regex, "_")); regex = "\\b"; s = "hello worpd 888 1 2 & ; 0 a b c d"; System.out.println("匹配之前:" + s); System.out.println("==========================================="); System.out.println(s.replaceAll(regex, "_")); regex = "\\B"; System.out.println(s.replaceAll(regex, "_")); } }
输出结果:
匹配之前:abcdefg ========================================= _defg abcde_ 匹配之前:hello worpd 888 1 2 & ; 0 a b c d =========================================== _hello_ _worpd_ _888_ _1_ _2_ & ; _0_ _a_ _b_ _c_ _d_ h_e_l_l_o w_o_r_p_d 8_8_8 1 2 _&_ _;_ 0 a b c d
2.5 量词
? : 出现了0次或者1次
+:出现了1次或者多次
*:出现了任意次
{n}:出现了正好n次
{n,m}:出现了n-m次
{n, };表示出现了至少n次
package com.wyh.day16; /* 元字符: 2.5 量词 ? : 出现了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 s = "baaabcdefaaaaaag"; System.out.println("匹配之前:" + s); System.out.println("======================================="); System.out.println(s.replaceAll(regex, "_")); regex = "^a+"; System.out.println(s.replaceAll(regex, "_")); regex = "^a*"; System.out.println(s.replaceAll(regex, "_")); //{n}:出现了正好n次 //需求:匹配一个字符串a字符连续出现了6 regex = "a{6}"; // aaaaaa System.out.println(s.replaceAll(regex, "*")); //{n,m}:出现了n-m次 regex = "a{3,4}"; // 匹配的是a连续出现的次数在3-4之间 System.out.println(s.replaceAll(regex, "*")); //{n, };表示出现了至少n次 regex = "a{6,}"; System.out.println(s.replaceAll(regex, "*")); //验证qq regex = "[1-9][0-9]{4,9}"; s = "1165872335"; System.out.println(s.replaceAll(regex, "匹配成功")); } }
输出结果:
匹配之前:baaabcdefaaaaaag ======================================= _baaabcdefaaaaaag baaabcdefaaaaaag _baaabcdefaaaaaag baaabcdef*g b*bcdef*aag baaabcdef*g 匹配成功 Process finished with exit code 0
2.6 分组:()
package com.wyh.day16; /* 元字符: 2.6 分组:() */ public class RegularDemo8 { public static void main(String[] args) { //它表示匹配的内容是ab加上1-2个c String reagex = "abc{1,2}"; String s = "abcccccABC123123ABCabcccccABC123123ABCabcccccABC123123ABCabcabcabc123"; System.out.println("匹配之前:\n" + s); System.out.println("==========================================================="); System.out.println(s.replaceAll(reagex, "_")); //加上小括号表示分组 //表示abc整体出现了1-2次 reagex = "(abc){1,2}"; System.out.println(s.replaceAll(reagex, "_")); reagex = "ABC(abc){1,}"; //ABCabcabc System.out.println(s.replaceAll(reagex, "_")); //matches System.out.println(s.matches(reagex)); } }
输出结果:
匹配之前: abcccccABC123123ABCabcccccABC123123ABCabcccccABC123123ABCabcabcabc123 =========================================================== _cccABC123123ABC_cccABC123123ABC_cccABC123123ABC___123 _ccccABC123123ABC_ccccABC123123ABC_ccccABC123123ABC__123 abcccccABC123123_ccccABC123123_ccccABC123123_123 false
2.7 反向引用(用来取值的)
$: 取值,取对应分组号中的值,每一个分组的编号从1开始
需求:2022-01-23 ---> 01/23/2022
/* 需求:2022-01-23 ---> 01/23/2022 使用正则中的反向引用完成 */ public class RegularDemo9 { public static void main(String[] args) { //2022-01-23 String regex = "(\\d{4})-(\\d{2})-(\\d{2})"; String s = "2022-01-23 2022-02-24"; System.out.println(s.replaceAll(regex,"$2/$3/$1")); //分组中如果我不想让它生成编号 ?: regex = "(\\d{4})-(?:\\d{2})-(\\d{2})"; // System.out.println(s.replaceAll(regex,"$2/$3/$1")); System.out.println(s.replaceAll(regex,"$2/$1")); } }
输出结果:
01/23/2022 02/24/2022 23/2022 24/2022
3、正则表达式在java中的应用
在java中是如何让使用正则表达式来实现相关操作的?
1、字符串的查找操作:Pattern和Matcher
2、字符串的匹配操作:可以使用该字符串的matches方法
3、字符串的替换操作:字符串String类中有replaceAll()方法和replaceFirst()方法
4、字符串的分割工作:字符串String类中有split()方法
package com.wyh.day16; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; /* 3、正则表达式在java中的应用 在java中是如何让使用正则表达式来实现相关操作的? 1、字符串的查找操作:Pattern和Matcher 2、字符串的匹配操作:可以使用该字符串的matches方法 3、字符串的替换操作:字符串String类中有replaceAll()方法和replaceFirst()方法 4、字符串的分割工作:字符串String类中有split()方法 */ public class RegularDemo10 { public static void main(String[] args) { String regex = "\\w{3,}"; String s = "abcd123"; System.out.println(s.matches(regex)); regex = "[a-z]{2,}"; s = "abc defg hello111"; System.out.println(s.replaceAll(regex, "_")); System.out.println(s.replaceFirst(regex, "_")); s = "abc sbdf 123ab sa123bddss &"; String[] s1 = s.split(" "); //工具类遍历数组 System.out.println(Arrays.toString(s1)); s = "abc sbdf 123ab sa123bddss &"; String[] s2 = s.split("a"); //工具类遍历数组 System.out.println(Arrays.toString(s2)); //Pattern和Matcher regex = "\\w{3,7}"; Pattern compile = Pattern.compile(regex); Matcher matcher = compile.matcher("abcd123"); System.out.println(matcher.matches()); } }
输出结果:
true _ _ _111 _ defg hello111 [abc, sbdf, 123ab, sa123bddss, &] [, bc sbdf 123, b s, 123bddss &] true
4、正则表达式经典练习
题目:将字符串“我我我我我我我..........我.......要要要要要..................要要要要...学习习习习.......习习习习习习习习编程程程程程程.......程程程程程程程程程”变成“我要学习编程”
分析:1、先将....去了 "\.+" 2、将叠词只取一个:(.)\1+; 反向引用取$1
package com.wyh.day16; /* 正则表达式练习: 题目:将字符串“我我我我我我我..........我.......要要要要要................. .要要要要...学习习习习.......习习习习习习习习编程程程程程程.......程程程程程程程程程”变成“我要学习编程” */ public class RegularDemo11 { public static void main(String[] args) { String s = "我我我我我我我..........我.......要要要要要..................要要要要...学习习习习.......习习习习习习习习编程程程程程程.......程程程程程程程程程"; //1、先将.去掉 String regex = "\\.+"; String s1 = s.replaceAll(regex, ""); System.out.println(s1); //2、合并叠词 regex = "(.)\\1+"; String s2 = s1.replaceAll(regex, "$1"); System.out.println(s2); } }
输出结果:
我我我我我我我我要要要要要要要要要学习习习习习习习习习习习习编程程程程程程程程程程程程程程程 我要学习编程
枚举类型
1、当一个类的对象只有有限个的时候,确定的,我们就可以把这个类定义为枚举类
举例:
星期:Monday(星期一)....Sunday(星期日)
性别:Man(男),Woman(女)
季节:Spring(春天)...winter(冬天)
时间,月份,就职状态...
2、当需要定义一组常量的时候,强烈建议使用枚举
如何定义一个枚举类?
根据JDK的版本不同,实现的方式不同
1、在JDK1.5之前,自定义一个枚举类
2、在JDK1.5之后,通过java提供了一个叫做enum的关键字创建枚举类
自定义一个枚举类: package com.wyh.day16; /* 自定以一个季节枚举类 */ public class EnumDemo1 { public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); System.out.println(spring.getSEASON_NAME()); System.out.println(spring.getSEASON_DESC()); } } class Season{ //2、创建Seanson的成员变量,必须把它定义为常量 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("夏天","烈日炎炎"); public static final Season AUTUMN = new Season("秋天","秋高气爽"); public static final Season WINTER = new Season("冬天","白雪皑皑"); //4、只提供公共的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 + '\'' + '}'; } }
输出结果:
Season{SEASON_NAME='春天', SEASON_DESC='春暖花开'} 春天 春暖花开
JDK1.5之后:通过关键字enum定义枚举类
package com.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、在每个枚举对象中实现