- 第13章 常用类
- 第14章 集合
- 第15章 泛型
目录
第13章 常用类
13.1 包装类
- 基本数据类型所对应的引用数据类型
- Object 可统一所有数据,包装类的默认值是null
13.1.1 类型转换与装箱、拆箱
- 8种包装类提供不用类型间的转换方式
- Number父类中提供的6个共性方法
2.parseXXX( )
静态方法
3.valueOf( )
静态方法- 注意:需保证类型兼容,否则抛出NumberFormatException异常
psvm(String[] args){
// 装箱, 基本类型 → 引用类型
// 基本类型
int num1 = 18;
// 使用Integer类创建对象
Integer integer1 = new Integer(num1);
Integer integer2 = Integer.valueOf(num1);
// 拆箱, 引用类型 → 基本类型
Integer integer3 = new Integer(100);
int num2 = integer3.intValue();
// 上述为jdk1.5之前方法,之后提供了自动装箱拆箱
int age = 30;
// 自动装箱
Integer integer4 = age;
// 自动拆箱
int age2 = integer4;
// 基本类型和字符串之间转换
// 1. 基本类型转成字符串
int n1 = 100;
// 1.1 使用+号
String s1 = n1 + "";
// 1.2 使用Integer中的toString()方法
String s2 = Integer.toString(n1);
String s2 = Integer.toString(n1, x); // x为进制要求
// 2. 字符串转成基本类型
String str = "150";
// 使用Integer.parseXXX();
int n2 = Integer.parseInt(str);
// boolean 字符串形式转成基本类型,"true" ---> true 非“true ———> false
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
}
13.1.2 整数缓冲区
- Java预先创建了256个常用的证书包装类型对象
- 在实际应用当中,对已创建的对象进行复用
psvm(String[] args){
// 面试题
Integer integer1 = new Integer(100);
Integer integer2 = new Integer(100);
sout(integer1 == integer2); // false
Integer integer3 = new Integer(100);// 自动装箱
// 相当于调用 Integer.valueOf(100);
Integer integer4 = new Integer(100);
sout(integer3 == integer4); // true
Integer integer5 = new Integer(200);// 自动装箱
Integer integer6 = new Integer(200);
sout(integer5 == integer6); // false
// 因为缓存区数组 [-128, 127] 在这之内地址一样
}
13.2 String类
13.2.1 常用方法
- 字符串是常量,创建之后不可改变
- 字符串字面值存储在字符串池中,可以共享
String s = "Hello";
产生一个对象,字符串池中存储String s = new String("Hello");
产生两个对象,堆、池各一个
// 1. length(); 返回字符串长度
// 2. charAt(int index); 返回某个位置的字符
// 3. contains(String str); 判断是否包含某个字符串
String content = "java是最好的语言, java no1";
sout(content.length()); // 10
sout(content.charAt(content.length() - 1)); // 言
sout(content.contains("java")); // true
// 4. toCharArray(); 返回字符串对应数组
// 5. indexOf(); 返回子字符串首次出现的位置
// 6. lastIndexOf(); 返回字符串最后一次出现的位置
sout(content.toCharArray());
sout(content.indexOf"java")); // 0
sout(content.indexOf("java", 4)); // 从索引4开始找 返回12
sout(content.lastIndexOf("java")); // 12
// 7. trim(); //去掉字符串前后空格
// 8. toUpperCase(); toLowerCase(); 转换大小写
// 9. endWith(str); startWith(str); 判断是否以str 结尾、开头
String ct = " hello world ";
sout(ct.trim()); // "hello world"
sout(ct.toUpperCase()); // HELLO WORLD
sout(ct.toLowerCase()); // hello world
sout(ct.endWith("world")); // true
sout(ct.startWith("hello")) // true
// 10. replace(char old, char new); 用心的字符或字符串替换旧的字符或字符串
// 11. split(); 对字符串拆分
sout(content.replace("java", "php")); // php是最好的语言, php no1
String say = "java is the best language";
String[] arr = arr.say.split(" "); // "[ ,]+" 表示空格 逗号切分 +号表示切分可以多个 比如多个空格
sout(arr.length); // 5
for(String string : arr){
sout(string);
}
// 打印出
//java
//is
//the
//best
//language
// 补充两个equals/compareTo();比较大小
String s1 = "hello";
String s2 = "HELLO";
sout(s1.equalsIgnoreCase(s2));// 忽略大小写比较true
// compareTo(); 两字符不同时比较字符字典序的ascii码
// 字符相同时比较长度 返回差值
13.2.2 案例演示
需求:
- 已知String str = "this is a text";
- 将str中的单词单独获取
- 将str中的text替换成practice
- 在text前面插入一个easy
- 将每个单词的首字母改为大写
psvm(String[] args){
String str = "this is a text";
// 2.
String[] arr = str.split(" ");
for(String s : arr){
sout(s);
}
// 3.
String str2 = str.replace("text", "practice");
// 4.
String str3 = str.replace("text", "easy text");
// 5.
for(int i = 0; i < arr.length; i ++){
char first = arr[i].charAt(0);
char upperfirst = Character.toUpperCase(first);
String new = upperfirst + arr[i].substring(1);
}
}
13.2.3 可变字符串
- StringBuffer : 可变长字符串,运行效率慢、线程安全
- StringBuilder : 可边长字符串、运行快、线程不安全
效率都比String高且节省内存
psvm(String[] args){
// StringBuffer 和 StringBuilder 用法一致
StringBuffer sb = new StringBuffer();
// 1. append(); 追加
sb.append("java no1");
// 2. insert(); 添加、插入
sb.insert(0, "在第一个位置插入");
// 3.replace(); 替换
sb.replace(0, 9, str); // 左闭右开
// 4. delete(); 删除
sb.delete(0, 5); // 左闭右开
// 5. 清空
sb.delete(0, sb.length());
}
13.3 BigDecimal类
- 位置
java.math
包中- 作用 精确计算浮点数
- 创建方式
BigDecimal bd = new BigDecimal("1.0");
BigDecimal bd1 = new BigDecimal("1.0"); // 需用字符串
BigDecimal bd2 = new BigDecimal("0.9");
// 减法
BigDecimal r1 = bd1.subtract(bd2);
sout(r1); // 0.1
// 加法
BigDecimal r2 = bd1.add(bd2);
//乘法
BigDecimal r3 = bd1.multiply(bd2);
// 除法
BigDecimal r4 = new BigDecimal("1.4").subtract(new BigDecimal("0.5")).divide(new BigDecimal("0.9"), x, BigDecimal.ROUND_HALF_UP);
//除不尽时 x填保留位数 后面为四舍五入之意
13.4 Date类
Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法都已经被Calendar类中的方法所取代
时间单位:1s = 1,000ms = 1,000,000 μs = 1,000,000,000 = ns
psvm(String[] args){
// 1 创建Date对象
Date date1 = new Date();
sout(date1.toString()); //WED Sept 02 22:25:23 CST 2020
sout(date1.toLocaleString()); // 已过时 但也能用 2020-9-2
// 创建昨天的
Date date2 = new Date(date1.getTime() - (60*60*24*1000));
sout(date2.toLocaleString());
// 2 方法after before
boolean b1 = date.after(date2);
sout(b1); //true
boolean b2 = date1.before(date2);
sout(b2); //false
// 比较compareTo();
int d = date1.compareTo(date1);
sout(d); // 多的为1 少的为 -1
// 比较是否相等 equals()
boolean b3 = date1.equals(date2);
sout(b3); // false
}
13.5 Calender
- Calendar提供了获取或设置各种日历字段的方法
- 构造方法
protected Calendar();
由于是protected 所以无法直接创建- 其他方法
psvm(String[] args){
// 1. 创建 Calendar 对象
Calendar calendar = Calendar.getInstance();
sout(calendar.getTime().toLocaleString());
// 2. 获取时间信息
// 获取年
int year = calendar.get(Calendar.YEAR);
// 获取月 从 0 - 11
int month = calendar.get(Calendar.MONTH);
// 日
int month = calendar.get(Calendar.DAY_OF_MONTH);
// 小时
int hour = calendar.get(Calendar.HOUR_OF_DAY);
// 分钟
int minute = calendar.get(Calendar.MINUTE);
// 秒
int second = calendar.get(Calendar.SECOND);
// 3. 修改时间
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.DAY_OF_MONTH, x);
// 4. add修改时间
calendar2.add(Calendar.HOUR, x); // x为正就加 负就减
// 5. 补充方法
int max = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);// 月数最大天数
int min = calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);
}
13.6 SimpleDateFormat
- SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类
- 进行格式化(日期→文本)、解析(文本→日期)
- 常用的时间模式字母
psvm(String[] args){
// 1. 创建对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH-mm-ss");
// 2. 创建Date
Date date = new Date();
// 格式化date(日期→字符串)
String str = sdf.format(date);
sout(str);
// 解析(字符串→时间)
Date date2 = sdf.parse("1948/03/12");
sout(date2);
}
13.7 System类
主要用于获取系统的属性数据和其他操作,构造方法私有的
psvm(String[] args){
//arraycopy 复制
//src-原数组 srcPos-从哪个位置开始复制0 dest-目标数组 destPos-目标数组的位置 length-复制的长度
int[] arr = {20, 18, 39, 3};
int[] dest = new int [4];
System.arraycopy(src, srcPos, dest, destPos, length);
sout(arr, 4, dest, 4, 4)
// Arrays.copyOf(original, newLength)
}
第14章 集合
14.1 介绍
概念:对象的容器,实现了对对象常用的操作
和数组的区别:
- 数组长度固定,集合长度不固定
- 数组可以存储基本类型和引用类型,集合只能存储引用类型
14.2 位置
14.2.1 Collection 父接口
特点:代表一组任意类型的对象,无序、无下标、不能重复。
创建集合
Collection collection = new ArrayList();
常用方法
添加元素
collection.add();
删除元素
collection.remove();
collection.clear();
遍历元素(重点)
使用增强for(因为无下标)
for(Object object : collection){ }
使用迭代器
//haNext(); 有没有下一个元素 //next(); 获取下一个元素 //remove(); 删除当前元素 Iterator it = collection.iterator(); while(it.hasNext()){ String object = (String)it.next(); //强转 // 可以使用it.remove(); 进行移除元素 // collection.remove(); 不能用collection其他方法 会报并发修改异常 }
判断
collection.contains();
collection.isEmpty();
14.2.2 List子接口
特点:有序、有下标、元素可重复
创建集合对象
List list = new ArrayList<>( );
常用方法
- 添加元素
list.add( );
会对基本类型进行自动装箱- 删除元素 可以用索引
list.remove(0)
- 当删除数字与索引矛盾时 对数字强转
list.remove((Object) 10)
或list.remove(new Integer(10))
- 遍历
for(int i = 0; i < lise.size(); i++){ sout(list.get(i)); }
- 使用for遍历
for(Object list: collection){ }
- 使用迭代器
Iterator it = collection.iterator(); while(it.hasNext()){ String object = (String)it.next(); //强转 // 可以使用it.remove(); 进行移除元素 // collection.remove(); 不能用collection其他方法 会报并发修改异常 }
- 使用列表迭代器 💡(注意和迭代器区别)
ListIterator li = list.listIterator(); while(li.hasNext()){ System.out.println(li.nextIndex() + ":" + li.next()); //从前往后遍历 } while(li.hasPrevious()){ System.out.println(li.previousIndex() + ":" + li.previous()); //从后往前遍历 }
- 获取
list.indexOf( );
- 返回子集合
sublist(x, y);
左闭右开List subList = list.subList(1, 3);
返回索引 1、2
14.2.3 List实现类
- ArrayList 【重点】
- 数组结构实现,必须要连续空间,查询快、增删慢
- jdk1.2版本,运行效率块、线程不安全
- Vector
- 数组结构实现,查询快、增删慢
- jdk1.0版本,运行
- LinkedList
- 双向链表结构实现,无需连续空间,增删快,查询慢
ArrayList
创建集合
ArrayList arrayList = new ArrayList<>();
添加元素
arrayList.add();
删除元素
arrayList.remove(new Student("name", 10));
这里重写了 equals(this == obj) 方法
public boolean equals(Object obj){ //1 判断是不是同一个对象 if(this == obj){ return true; } //2 判断是否为空 if(obj == null){ return false; } //3 判断是否是Student类型 if(obj instanceof Student){ Student == (Student)obj; //4 比较属性 if(this.name.equals(s.getName()) && this.age == s.getAge()){ return true; } } //5 不满足条件返回false return false; }
3.遍历元素【重点】
使用迭代器
Iterator it = arrayList.iterator(); while(it.hasNext()){ Student s = (Student)it.next(); //强转 }
2.列表迭代器
ListIterator li = arrayList.listIterator(); while(li.hasNext()){ Student s = (Student)li.next(); //从前往后遍历 } while(li.hasPrevious()){ Student s = (Student)li.previous();//从后往前遍历 }
4.判断
arrayList.contains();
和arrayList.isEmpty();
5.
查找
arrayList.indexof();
14.2.4 Vector
创建集合
Vector vector = new Vector<>();
增加、删除、判断同上
遍历中枚举器遍历
Enumeration en = vector.elements(); while(en.hasMoreElements()){ String o = (String)en.nextElement(); sout(o); }
14.2.5 LinkedList
创建链表集合
LinkedList li = new LinkedList<>();
常用方法与List一致
第15章 泛型
15.1 介绍
- 本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类、泛型接口、泛型方法
- 语法 T成为类型占位符,表示一种引用类型,可以写多个逗号隔开
- 好处 1. 提高代码重用性 2. 防止类型转换异常,提高代码安全性
15.1.1 泛型类
// 写一个泛型类
public class MyGeneric<T>{
//使用泛型T
//1 创建变量
T t;
//2 泛型作为方法的参数
public void show(T t){
sout(t);
}
//3 泛型作为方法的返回值
public T getT(){
return t;
}
}
// 使用泛型类
public class TestGeneric{
public static void main(String[] args){
//使用泛型类创建对象
// 注意: 1. 泛型只能使用引用类型
// 2. 不用泛型类型对象之间不能相互赋值
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t = "hello";
myGeneric.show("hello world!");
String string = myGeneric.getT();
MyGeneric<Integer> myGeneric2 = new MyGeneric<Integer>();
myGeneric2.t = 100;
myGeneric2.show(200);
Integer integer = myGeneric2.getT();
}
}
15.1.2 泛型接口
语法:接口名
注意:不能泛型静态常量
15.1.3 泛型方法
语法: 返回值类型
public class MyGenericMethod{
//泛型方法
public <T> T show(T t){
sout("泛型方法" + t);
return t;
}
}
//调用
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show("字符串");// 自动类型为字符串
myGenericMethod.show(200);// integer类型
myGenericMethod.show(3.14);// double类型
15.2 泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致
特点:
- 编译时即可检查,而非运行时抛出异常
- 访问时,不必类型转换(拆箱)
- 不同泛型之间应用不能相互赋值,泛型不存在多态
15.2.1 Set集合
特点:无序、无下标、元素不可重复
方法:全部继承自Collection中的方法
增、删、遍历、判断与collection一致
15.2.2 HashSet [重点]
存储结构:哈希表(数组+链表+红黑树)
存储过程(重复依据)
- 根据hashCode计算保存的位置,如果位置为空,直接保存,若不为空,进行第二步
- 再执行equals方法,如果equals为true,则认为是重复,否则形成链表
特点
- 基于HashCode计算元素存放位置
- 利用31这个质数,减少散列冲突
- 31提高执行效率
31 * i = (i << 5) - i
转为移位操作- 当存入元素的哈希码相同时,会调用equals进行确认,如果结果为true,则拒绝后者存入
新建集合
HashSet<String> hashSet = new HashSet<String>();
添加元素
hashSet.add( );
删除元素
hashSet.remove( );
遍历操作
1. 增强for
for( type type : hashSet)
2. 迭代器
Iterator<String> it = hashSet.iterator( );
判断
hashSet.contains( );
hashSet.isEmpty();
15.2.3 TreeSet
特点
- 基于排列顺序实现元素不重复
- 实现SortedSet接口,对集合元素自动排序
- 元素对象的类型必须实现Comparable接口,指定排序规则
- 通过CompareTo方法确定是否为重复元素
存储结构:红黑树
创建集合
TreeSet<String> treeSet = new TreeSet<>()
添加元素
treeSet.add();
删除元素
treeSet.remove();
遍历 1. 增强for 2. 迭代器
判断
treeSet.contains();
补充:TreeSet集合的使用
Comparator 实现定制比较(比较器)
Comparable 可比较的
// 重写compare
@override
public int compare(Person o1, Person o2){
int n1 = o1.getAge()-o2.getAge();
int n2 = o1.getName().comareTo(o2.getName());
return n1 == 0 ? n2 : n1;
}
15.2.4 Map
Map接口的特点
1. 用于存储任意键值对(key - value) 2. 键:无序、无下标、不允许重复(唯一) 3. 值:无序、无下标、允许重复
方法:
1. V put(K key, V value) 将对象存到集合中,关联键值 2. Object get(Object key) 根据键获得对应的值 3. Set<K> 返回所有的Key 4. Collection<V> values() 返回包含所有值的Collection集合 5. Set<Map.Entry<K, V>> 键值匹配的Set集合
15.2.5 Map接口的使用
//创建Map集合
Map<String, String> map = new HashMap<>();
// 1. 添加元素
map.put("cn", "中国");
map.put("uk", "英国");
map.put("cn", "zhongguo"); // 会替换第一个
// 2. 删除
map.remove("uk");
// 3. 遍历
// 3.1 使用KeySet()
//Set<String> keyset = map.keySet(); // 所有Key的set集合
for(String key : map.keyset){
sout(key + "---" + map.get(key));
}
// 3.2 使用entrySet()
//Set<Map.Entry<String, String>> entries = map.entrySet();
for(Map.Entry<String, String> entry : map.entries){
sout(entry.getKey() + "---" + entry.getValue();
}
15.2.6 HashMap [重点]
存储结构:哈希表(数组+链表+红黑树)
使用key可使hashcode和equals作为重复
增、删、遍历、判断与上述一致
原码分析总结:
- HashMap刚创建时,table是null,节省空间,当添加第一个元素时,table容量调整为16
- 当元素个数大于阈值(16*0.75 = 12)时,会进行扩容,扩容后的大小为原来的两倍,目的是减少调整元素的个数
- jdk1.8 当每个链表长度 >8 ,并且数组元素个数 ≥64时,会调整成红黑树,目的是提高效率
- jdk1.8 当链表长度 <6 时 调整成链表
- jdk1.8 以前,链表时头插入,之后为尾插入
15.2.7 Hashtable
线程安全,运行效率慢;不允许null作为key或是value
15.2.8 Properties
hashtable的子类,要求key和value都是string,通常用于配置文件的读取
15.2.9 TreeMap
实现了SortedMap接口(是map的子接口),可以对key自动排序
15.3 Collection工具类
概念:集合工具类,定义了除了存取以外的集合常用方法
直接二分查找
int i = Collections.binarySearch(list, x);
成功返回索引其他方法 : copy复制、reverse反转、shuffle打乱
// list转成数组 Integer[] arr = list.toArray(new Integer[10]); sout(arr.length); sout(Array.toString(arr)); // 数组转成集合 // 此时为受限集合,不能 添加和删除! String[] name = {"张三","李四","王五"}; List<String> list2 = Arrays.asList(names); // 把基本类型数组转为集合时,需要修改为包装类 Integer[] nums = {100, 200, 300, 400, 500}; List<Integer> list3 = Arrays.asList(nums);