第九章 使用基础API
一、枚举类
一、枚举:jdk 1.5 后的特性,可以定义有限数量的可穷举数据集
简而言之,当确定一个类有几个对象时,使用枚举
1、自定义枚举
1) 私有化构造器
2) 类的内部创建对象
2、使用 enum 关键字
valueOf(String name) : 通过字符串类型的枚举类对象名称,获取对应的枚举类对象
values() : 获取当前枚举类中所有的枚举类对象
3、枚举类实现接口
public class EnumTest {
public static void main(String[] args) {
/*Season spring = Season.SPRING;
System.out.println(spring);
Season summer = Season.SUMMER;
System.out.println(summer);*/
/*Season1 spring = Season1.SPRING;
System.out.println(spring);*/
/*Season2 spring = Season2.SPRING;
System.out.println(spring);*/
//switch-case
/*Season2 sea = Season2.SPRING;
switch(sea){
case SPRING:
System.out.println("春天");
break;
case SUMMER:
System.out.println("夏天");
break;
case AUTUMN:
System.out.println("秋天");
break;
case WINTER:
System.out.println("冬天");
break;
}*/
//枚举类常用方法
/*Season2 spring = Season2.valueOf("SPRING");
System.out.println(spring);*/
Season3[] seasons = Season3.values();
for (Season3 season : seasons) {
//System.out.println(season);
season.show();
}
}
}
package com.atguigu.java;
//自定义枚举类
public class Season {
private String seasonName;
private String seasonDesc;
//2. 类的内部创建对象
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("冬天", "冬天雪花飘");
//1. 私有化构造器
private Season(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public void setSeasonName(String seasonName) {
this.seasonName = seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
public void setSeasonDesc(String seasonDesc) {
this.seasonDesc = seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
package com.atguigu.java;
public enum Season1 {
//2. 类的内部创建对象
SPRING("春天", "春眠不觉晓"),
SUMMER("夏天", "处处蚊子咬"),
AUTUMN("秋天", "秋天叶子黄"),
WINTER("冬天", "冬天雪花飘");
private String seasonName;
private String seasonDesc;
//1. 私有化构造器
private Season1(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public void setSeasonName(String seasonName) {
this.seasonName = seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
public void setSeasonDesc(String seasonDesc) {
this.seasonDesc = seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
package com.atguigu.java;
public enum Season2 {
SPRING,
SUMMER,
AUTUMN,
WINTER;
}
package com.atguigu.java;
//枚举类实现接口
public enum Season3 implements MyInterface{
SPRING{
public void show(){
System.out.println("春天");
}
},
SUMMER{
public void show(){
System.out.println("夏天");
}
},
AUTUMN{
public void show(){
System.out.println("秋天");
}
},
WINTER{
public void show(){
System.out.println("冬天");
}
};
/*public void show(){
System.out.println("季节");
}*/
}
二、注解
一、注解:jdk1.5后的特性,是一个代码级别的说明。是一个元数据。
在java 中以 “@注解名” 的方式呈现
String name = “atguigu”;
1、JDK 内置的常用注解
@Override : 用于描述方法,说明该方法必须是重写方法
@Deprecated : 用于注解属性、方法、类。 说明已经过时
@SuppressWarnings : 用于抑制编译器警告
2、自定义注解
格式:
public @interface MyAnnotation{}
3、元注解
@Retention : 描述注解的生命周期
@Target: 描述注解可以修饰哪些程序元素
@Documented :描述注解可以随之生成说明文档
@Inherited :描述注解拥有继承性
public class AnnotationTest {
public static void main(String[] args) {
Person p = new Person();
p.name = "张三";
System.out.println(p.name);
@SuppressWarnings("unused")
int num = 0;
}
}
@Deprecated
@MyAnnotation
class Person{
@Deprecated
String name;
@Override
public String toString() {
return "Person{}";
}
@MyAnnotation("睡觉方法")
public void sleep(){
System.out.println("睡觉");
}
}
class Student extends Person{
@Override
public void sleep(){
System.out.println("学生上课偷偷睡觉");
}
}
package com.atguigu.java;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotation {
String value() default "atguigu";
}
三、包装类
一、包装类(包裹类 Wrapper):
Java 为八种基本数据类型提供了对应的包装类,意味着可以创建对应的对象,使用起来方便
基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
1、基本数据类型与包装类之间的转换
装箱:将基本数据类型转换成对应的包装类
①使用对应包装类的构造器
②通过对应包装类的静态方法 valueOf()
拆箱:将包装类转换成对应的基本数据类型
①通过对应包装类的 xxxValue() 方法。 xxx:代表基本数据类型
2、自动装箱与自动拆箱(jdk1.5后)
3、基本数据类型、包装类 与 String 之间的转换
1) 基本数据类型、包装类 转换成 String
①对应包装类的静态方法 toString()
② String str4 = i2 + “”;
③使用 String 类的静态方法 valueOf()
2) String 转换成 基本数据类型、包装类
①使用对应包装类的构造器
②使用对应包装类的静态方法 parseXxx() 。 Xxx:代表基本数据类型,注意:没有 parseChar()
③使用对应包装类的静态方法 valueOf()
public class WrapperTest {
//String 转换成 基本数据类型、包装类
@Test
public void test7(){
String str = "123";
Integer num = new Integer(str);
System.out.println(num);
String str2 = "15.6f";
Float f = new Float(str2);
System.out.println(f);
String str3 = "trueadsfsda";
Boolean b = new Boolean(str3); //注意:该字符串除了 true 其他都为 false
System.out.println(b);
System.out.println("--------------------------------");
Integer num2 = Integer.parseInt(str);
System.out.println(num2);
Float f2 = Float.parseFloat(str2);
System.out.println(f2);
System.out.println("--------------------------------");
Integer num3 = Integer.valueOf(str);
System.out.println(num3);
Float f3 = Float.valueOf(str2);
System.out.println(f3);
}
//基本数据类型、包装类 转换成 String
@Test
public void test6(){
int i = 10;
String str = Integer.toString(i);
System.out.println(str);
float f = 15.6f;
String str2 = Float.toString(f);
System.out.println(str2);
boolean b = true;
String str3 = Boolean.toString(b);
System.out.println(str3);
System.out.println("---------------------------------");
int i2 = 10;
String str4 = i2 + "";
System.out.println(str4);
System.out.println("---------------------------------");
String str5 = String.valueOf(i2);
System.out.println(str5);
}
//【面试题】
@Test
public void test5(){
//注意:Integer 低层提供了一个小的缓存,该缓存取值范围在(-128~127之间)
//若需要装箱值,在该取值范围内,则直接从缓存中取一个实例
//若超出该取值范围,则重新 new Integer() 的实例
Integer num1 = 100;
Integer num2 = 100;
System.out.println(num1 == num2);//true
Integer num3 = 130;
Integer num4 = 130;
System.out.println(num3 == num4);//false
}
//自动装箱与自动拆箱
@Test
public void test4(){
Integer num1 = 123; //自动装箱
int num2 = num1; //自动拆箱
}
//拆箱
@Test
public void test3(){
Integer num = new Integer(123);//装箱
int i = num.intValue();//拆箱
System.out.println(i);
Character ch = new Character('A');
char c = ch.charValue();
System.out.println(c);
Double d1 = new Double(15.6);
double d2 = d1.doubleValue();
}
//装箱
@Test
public void test2(){
int i = 10;
Integer num = Integer.valueOf(i);
System.out.println(num);
double d1 = 15.6;
Double d2 = Double.valueOf(d1);
System.out.println(d2);
}
//装箱
@Test
public void test1(){
int num = 10;
Integer newNum = new Integer(num);//装箱
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.toBinaryString(345));
System.out.println(Integer.toHexString(345));
float f = 15.6f;
Float f1 = new Float(f);//装箱
System.out.println(f1);
boolean b = true;
Boolean b2 = new Boolean(b);
System.out.println(b2);
}
}
四、String : 不可变的字符序列
String str1 = “abc”;
String str2 = new String(“abc”);
二者的区别:
str1 : 代表一个对象,至少在内存中开辟一块内存空间
(至少的意思是,"abc"存常量池,存储的方式是现在常量池中找,是否有 “abc”,
如果有,直接获取地址值,如果没有则重新开辟内存空间)。
str2 : 代表两个对象,至少在内存中开辟两块内存空间。
一、String类的常用方法
1、获取字符串的方法:
①String concat(String str):串接字符串
②String substring(int beginIndex):获取取字符串的子串
String substring(int beginIndex, endIndex) : 包含头不包含尾
③String toLowerCase()和String toUpperCase():转换为小写/大写
④String trim():删除首尾空格或制表符
2、搜索方法:
①int indexOf(int ch) : 获取指定字符在字符串中的位置,若没有指定的字符,返回 -1
int indexOf(int ch, int fromIndex) : 从指定位置开始搜索
int indexOf(String str)
int indexOf(String str, int fromIndex)
int lastIndexOf(int ch) : 反向获取指定字符位置
3、判断方法:
① boolean equals(Object obj):判断是否相等
boolean equalsIgnoreCase(String str):判断是否相等,不考虑大小写
② boolean contains(String str) :判断是否包含某字符串
③ boolean startsWith(String str)和 boolean endsWith(String str):判断是否以指定字符串开始/结尾
④ boolean isEmpty():判断字符串是否为空
4、其它方法:
①length():返回字符串长度
②char charAt(int index):返回索引处的字符
③将字符数组转换为字符串
构造器:
String(char[] ch)
String(char[] ch, offset, count) : 将数组中一部分转换为字符串, count 代表转几个
静态方法:
static String copyValueOf(char[] ch)
static String copyValueOf(char[] ch, offset, count)
static String valueOf(char[])
将字符串转换字符数组: char[] toCharArray()
④String replace(char oldCahr, char newCahr) : 替换字符串中字符
String replace(String oldStr, String oldStr):替换字符串中字符串
⑤String[] split(String r):根据指定符号切割
public class StringTest1 {
@Test
public void test8(){
String str = "abc,defb,cbcb,cbc";
System.out.println(str.replace('c', 'O'));
System.out.println(str.replace("bc", "OOOO"));
String[] strs = str.split(",");
for (String s : strs) {
System.out.println(s);
}
}
//将字符数组转换为字符串
//作业:查看api,查找字节数组与字符串之间的转换
@Test
public void test7(){
//将字符数组转换为字符串
char[] chs = {'a', 'b', 'c', 'd', 'e'};
String str = new String(chs);
System.out.println(str);
String str2 = new String(chs, 1, 2);
System.out.println(str2);
String str3 = String.valueOf(chs, 0, 3);
System.out.println(str3);
String str4 = String.copyValueOf(chs, 0, 3);
System.out.println(str4);
System.out.println("--------------------------------");
//将字符串转换成字符数组
String str5 = "abcdef";
char[] chars = str5.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
}
//4. 其它方法
@Test
public void test6(){
String str = "abcdef";
System.out.println(str.length());
char ch = str.charAt(0);
System.out.println(ch);
}
//3. 判断方法
@Test
public void test5(){
String str1 = "abc";
String str2 = new String("aBc");
boolean b = str1.equals(str2);
System.out.println(b);
System.out.println(str1.equalsIgnoreCase(str2));
String str3 = "abcdef";
System.out.println(str3.contains("abc"));
System.out.println(str3.startsWith("abc"));
System.out.println(str3.endsWith("def"));
String str4 = "";
System.out.println(str4.isEmpty());
}
//2. 搜索方法
@Test
public void test4(){
String str = "abcdefbcbcbc";
int i = str.indexOf('t');
System.out.println(i);
i = str.indexOf('c', 3);
System.out.println(i);
i = str.indexOf("bcddfdfd");
System.out.println(i);
i = str.lastIndexOf('c');
System.out.println(i);
}
//1. 获取字符串的方法:
@Test
public void test3(){
String str1 = "aBc";
String str2 = "def";
String str3 = str1.concat(str2);
System.out.println(str3);//abcdef
String str4 = str3.substring(2);
System.out.println(str4);
String str5 = str3.substring(2, 4);
System.out.println(str5);
String str6 = str3.toLowerCase();
System.out.println(str6);
System.out.println(str3.toUpperCase());
String str7 = " abcdef\t\t";
System.out.println(str7);
String str8 = str7.trim();
System.out.println(str8);
}
@Test
public void test2(){
String str = "abc";
String str1 = "def";
String str2 = "ddd";
String str3 = "fff";
String str5 = str + str1 + str2 + str3;//
}
@Test
public void test1(){
String str1 = "abc";
String str2 = new String("abc");
String str4 = new String("abc");
String str3 = "abc";
System.out.println(str1 == str2);//false
System.out.println(str1 == str3);//true
System.out.println(str2 == str4);//false
}
}
五、String 的常见算法:
模拟一个trim方法,去除字符串两端的空格。
将一个字符串进行反转。将字符串中指定部分进行反转。比如将“abcdefg”反转为”abfedcg”
获取一个字符串在另一个字符串中出现的次数。
比如:获取“ ab”在 “abkkcadkabkebfkabkskab”
中出现的次数
获取两个字符串中最大相同子串。比如:
str1 = "abcwerthelloyuiodef“;str2 = “cvhellobnm”
提示:将短的那个串进行长度依次递减的子串与较长
的串比较。
对字符串中字符进行自然顺序排序。
提示:
1)字符串变成字符数组。
2)对数组排序,选择,冒泡,Arrays.sort();
3)将排序后的数组变成字符串。
package com.atguigu.java;
import java.util.Arrays;
public class StringTest {
public static void main(String[] args) {
System.out.println(myTrim(" "));
System.out.println(revString("abcdefg", 2, 5));
System.out.println(getCount("aba", "abkkcadkabkebfkabkskababab"));
System.out.println(getMaxStr("abcwerthelloyuiodef", "cvhellobnm"));
System.out.println(mySort("defacb"));
}
public static String mySort(String str){
char[] chs = str.toCharArray();
Arrays.sort(chs);
return new String(chs);
}
public static String getMaxStr(String str1, String str2){
//1. 判断并获取长串和短串
String maxStr = str1.length() > str2.length() ? str1 : str2;
String minStr = str1.length() > str2.length() ? str2 : str1;
//2. 获取短串的长度
int minLength = minStr.length();
//3. 外层循环判断比较多少轮
for(int i = 0; i < minLength; i++){
//4. 短串长度依次递减
for(int x = 0, y = minLength - i; y <= minLength; x++, y++){
String newStr = minStr.substring(x, y);
if(maxStr.contains(newStr)){
return newStr;
}
}
}
return null;
}
public static int getCount(String str1, String str2){
int count = 0;
int index = 0;
while((index = str2.indexOf(str1, index)) != -1){
count++;
index += 1;
}
return count;
}
public static String revString(String str, int start, int end){
char[] chs = str.toCharArray();
for(int i = start, j = end; i < j; i++, j--){
char ch = chs[i];
chs[i] = chs[j];
chs[j] = ch;
}
return new String(chs);
}
// abcdef
public static String myTrim(String str){
char[] chs = str.toCharArray();
int start = 0;
int end = chs.length - 1;
while(end <= start && chs[start] == ' '){
start++;
}
while(end <= start && chs[end] == ' '){
end--;
}
String newStr = str.substring(start, end+1);
return newStr;
}
}
六、其他类
java.util.Date : 日期类
java.text.DateFormat : 是一个抽象类
|–java.text.SimpleDateFormat : 时间/日期的格式化
java.util.Calendar(日历)类
java.lang.Math类 :
double ceil(double d) : 返回不小于d的最小整数
double floor(double d): 返回不大于d的最大整数
int round(float f) : 返回最接近f的int型(四舍五入)
long round(double d):返回最接近d的long型
double abs(double d):
double max(double d1, double d2) : 返回较大值
int min(int i1, int i2) : 返回较小值
double random() : 返回一个大于等于0.0并且小于1.0的随机数
java.math.BigInteger : 支持任意精度的整数
java.math.BigDecimal : 支持任意精度的浮点数
public class OtherTest {
@Test
public void testBigInteger(){
BigInteger bi = new BigInteger("12433241123");
BigDecimal bd = new BigDecimal("12435.351");
BigDecimal bd2 = new BigDecimal("11");
System.out.println(bi);
System.out.println(bd.divide(bd2,BigDecimal.ROUND_HALF_UP));
System.out.println(bd.divide(bd2,15,BigDecimal.ROUND_HALF_UP));
}
@Test
public void test4(){
double d = 15.6;
System.out.println(Math.ceil(d));
System.out.println(Math.floor(d));
System.out.println(Math.round(d));
System.out.println(Math.abs(-d));
System.out.println(Math.max(15.6, 22.22));
System.out.println(Math.min(15.6, 22.22));
double d1 = Math.random();
System.out.println(d1);
//生成一个 0-100 之前的随机整数
int num = (int)(Math.random() * 32 + 1);
System.out.println(num);
}
@Test
public void test3() {
Calendar calendar = Calendar.getInstance();
// 从一个 Calendar 对象中获取 Date 对象
Date date = calendar.getTime();
//使用给定的 Date 设置此 Calendar 的时间
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 8);
System.out.println("当前时间日设置为8后,时间是:" +
calendar.getTime());
calendar.add(Calendar.HOUR, 2);
System.out.println("当前时间加2小时后,时间是:" +
calendar.getTime());
calendar.add(Calendar.MONTH, -2);
System.out.println("当前日期减2个月后,时间是:" +
calendar.getTime());
}
@Test
public void test2() throws ParseException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
String strDate = sdf.format(date);
System.out.println(strDate);
Date newDate = sdf.parse(strDate);
System.out.println(newDate);
}
@Test
public void test1() {
Date date = new Date();
System.out.println(date);
long millis = date.getTime();
System.out.println(millis);
Date date1 = new Date(millis);
System.out.println(date1);
}
}
七、StringBuffer 和 StringBuilder
一、定义:
可变的字符序列。二者具有兼容的 API
**StringBuffer :**是线程安全的,因此效率低
StringBuilder : 是线程不安全的,因此效率高
StringBuffer 和 StringBuilder 的常用方法:
① StringBuffer append(String str) : 添加
StringBuffer insert(int offset, String str) : 插入
StringBuffer replace(int start, int end, String str):替换
② int indexOf(String str) :返回子串的位置索引
int lastIndexOf()
③ String substring(int start, int end):取子字符串序列
④ StringBuffer delete(int start, int end):删除一段字符串
StringBuffer deleteCharAt(int index):删除指定位置字符
⑤ String toString():转换为String对象
public class StringBufferTest {
@Test
public void test2(){
StringBuilder sb = new StringBuilder("abcdef");
String str = sb.substring(2, 5);
System.out.println(str);
sb.delete(2, 5);
sb.deleteCharAt(1);
System.out.println(sb);
String newStr = sb.toString();
System.out.println(newStr);
System.out.println(sb.length());
}
@Test
public void test1(){
String str = "abc";
StringBuffer sb = new StringBuffer(str);
sb.append("def").append(123).append(15.6f).append(true);
sb.insert(3, "OOO");
sb.replace(3, 6, "TTT");
sb.append("TTT");
int index = sb.indexOf("TTT");
int lastIndex = sb.lastIndexOf("TTT");
System.out.println(index);
System.out.println(lastIndex);
System.out.println(sb);
}
}
执行速度测试
package com.atguigu.java;
public class StringBufferTest2 {
public static void main(String[] args) {
String text = "";
long startTime = 0L;
long endTime = 0L;
StringBuffer buffer = new StringBuffer("");
StringBuilder builder = new StringBuilder("");
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
buffer.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间:" + (endTime - startTime));
}
}