Collection
是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素
JDK 不提供此接口的任何直接实现.它提供更具体的子接口(如Set和List)实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 Collection<String> c = new ArrayList <>(); Collection<String> set = new HashSet <>(); boolean b1 = c.add("A" ); boolean b2 = c.add("B" ); boolean b3 = c.add("A" ); c.addAll(List.of("X" , "Y" )); int n = c.size(); boolean empty = c.isEmpty(); boolean has = c.contains("A" ); boolean all = c.containsAll(List.of("A" ,"B" )); boolean r1 = c.remove("A" ); Collection<Integer> nums = new ArrayList <>(); nums.add(0 ); nums.add(1 ); nums.remove(0 ); ((List<Integer>)nums).remove(0 ); c.removeAll(List.of("A" ,"B" )); c.retainAll(List.of("X" )); c.clear(); c.removeIf(s -> s == null ); c.removeIf(s -> s.startsWith("A" )); Iterator<String> it = c.iterator(); while (it.hasNext()) { String s = it.next(); if (s.length() > 3 ) it.remove(); } for (String s : c) { ... } Object[] a1 = c.toArray(); String[] a2 = c.toArray(new String [0 ]); c.stream().filter(...).forEach(...);
迭代器以及遍历 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 Collection<String> c = new ArrayList <>(List.of("A" , "BB" , "CCC" , "DDDD" )); for (String s : c) { System.out.println(s); } int i = 0 ;for (String s : c) { System.out.println(i++ + ":" + s); }c.forEach(s -> System.out.println(s)); c.forEach(System.out::println); c.forEach((String s) -> { System.out.println(s); }); c.forEach(s -> { if (s.length() > 2 ) System.out.println(s); }); StringBuilder sb = new StringBuilder ();c.forEach(sb::append); c.removeIf(s -> s.length() > 2 ); Iterator<String> it = c.iterator(); while (it.hasNext()) { String s = it.next(); if (s == null ) continue ; if (s.length() > 2 ) { it.remove(); } } ListIterator<String> lit = ((List<String>)c).listIterator(); while (lit.hasNext()) { int idx = lit.nextIndex(); String s = lit.next(); if (s.length() > 2 ) lit.remove(); else lit.add("X" ); } lit.hasPrevious(); lit.previous(); List<String> list = new ArrayList <>(c); for (int i = list.size() - 1 ; i >= 0 ; i--) { if (list.get(i).length() > 2 ) list.remove(i); }
List集合
方法名
描述
void add(int index,E element)
在此集合中的指定位置插入指定的元素
E remove(int index)
删除指定索引处的元素,返回被删除的元素
E set(int index,E element)
修改指定索引处的元素,返回被修改的元素
E get(int index)
返回指定索引处的元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 List<Integer> li = new ArrayList <>(); li.add(1 ); li.add(2 ); li.remove(1 ); ListIterator<String> it = list.listIterator(); while (it.hasNext()){ String str = it.next(); if ("bbb" .equals(str)){ it.add("qqq" ); } }
LinkedList
方法名
说明
public void addFirst(E e)
在该列表开头插入指定的元素
public void addLast(E e)
将指定的元素追加到此列表的末尾
public E getFirst()
返回此列表中的第一个元素
public E getLast()
返回此列表中的最后一个元素
public E removeFirst()
从此列表中删除并返回第一个元素
public E removeLast()
从此列表中删除并返回最后一个元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 public class MyLinkedListDemo4 { public static void main (String[] args) { LinkedList<String> list = new LinkedList <>(); list.add("aaa" ); list.add("bbb" ); list.add("ccc" ); } private static void method4 (LinkedList<String> list) { String first = list.removeFirst(); System.out.println(first); String last = list.removeLast(); System.out.println(last); System.out.println(list); } private static void method3 (LinkedList<String> list) { String first = list.getFirst(); String last = list.getLast(); System.out.println(first); System.out.println(last); } private static void method2 (LinkedList<String> list) { list.addLast("www" ); System.out.println(list); } private static void method1 (LinkedList<String> list) { list.addFirst("qqq" ); System.out.println(list); } }
泛型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 class Box <T> { private final T value; Box(T value) { this .value = value; } T get () { return value; } } @FunctionalInterface interface Converter <T, R> { R convert (T t) ; } class Utils { static <T> T first (List<T> list) { return list.get(0 ); } static <T extends Comparable <T>> T max (T a, T b) { return a.compareTo(b) >= 0 ? a : b; } } Box<String> box = new Box <>("hello" ); String s = box.get();Converter<String, Integer> len = String::length; Converter<String, Integer> len2 = str -> str.length(); Integer n = len.convert("java" );List<Integer> nums = List.of(1 , 2 , 3 ); Integer first = Utils.first(nums);Integer max = Utils.max(3 , 7 );class Ye {}class Fu extends Ye {}class Zi extends Fu {}ArrayList<Ye> list1 = new ArrayList <>(); ArrayList<Fu> list2 = new ArrayList <>(); ArrayList<Zi> list3 = new ArrayList <>(); method(list1); list1.add(new Ye ()); list1.add(new Fu ()); list1.add(new Zi ()); public static void method (ArrayList<Ye> list) {}double sum (List<? extends Number> list) { double total = 0 ; for (Number num : list) total += num.doubleValue(); return total; } sum(List.of(1 , 2 , 3 )); sum(List.of(1.5 , 2.5 )); void addInts (List<? super Integer> list) { list.add(1 ); Object o = list.get(0 ); } List<Number> numberList = new ArrayList <>(); addInts(numberList); addInts(new ArrayList <Object>()); static <T> void copy (List<? super T> dest, List<? extends T> src) { for (T t : src) dest.add(t); }
数据结构
栈结构:先进后出,后进先出
队列结构:先进先出,后进后出
数组结构:查询快、增删慢
链表结构:查询慢、增删快
二叉树
二叉树中,任意一个节点的度要小于等于2
节点:在树结构中,每一个元素称之为节点
度:每一个节点的子节点数量称之为度
二叉查找树
每一个节点上最多有两个子节点
左子树上所有节点的值都小于根节点的值
右子树上所有节点的值都大于根节点的值
添加节点规则:小的存左边,大的存右边,一样的不存
遍历:
前序遍历:当前节点,左子节点,右子结点
中序遍历:左子节点,当前节点,右子结点
后序遍历:左子节点,右子结点,当前节点
层序遍历:一层一层的去遍历
平衡二叉树
二叉树左右两个子树的高度差不超过1
任意节点的左右两个子树都是一颗平衡二叉树
左旋:就是将根节点的右侧往左拉,原先的右子节点变成新的父节点,并把多余的左子节点出让,给已经降级的根节点当右子节点
右旋:就是将根节点的左侧往右拉,左子节点变成了新的父节点,并把多余的右子节点出让,给已经降级根节点当左子节点
平衡二叉树旋转的四种情况
左左
左左:当根节点左子树的左子树有节点插入,导致二叉树不平衡
如何旋转:直接对整体进行右旋即可
左右
左右:当根节点左子树的右子树有节点插入,导致二叉树不平衡
如何旋转:先在左子树对应的节点位置进行左旋,在对整体进行右旋
右右
右右:当根节点右子树的右子树有节点插入,导致二叉树不平衡
如何旋转:直接对整体进行左旋即可
右左
右左:当根节点右子树的左子树有节点插入,导致二叉树不平衡
如何旋转:先在右子树对应的节点位置进行右旋,在对整体进行左旋
红黑树
平衡二叉B树
每一个节点可以是红或者黑
红黑树不是高度平衡的,它的平衡是通过“自己的红黑规则”进行实现的
红黑规则
每一个节点或是红色的,或者是黑色的
根节点必须是黑色
红黑树中,所有空指针(null)在逻辑上均被视为指向一个黑色的虚拟叶子节点(NIL/哨兵节点),它不存数据,仅作为路径终点统一黑高计算基准。
如果某一个节点是红色,那么它的子节点必须是黑色(不能出现两个红色节点相连的情况)
对每一个节点,从该节点到其所有后代叶节点的简单路径上,均包含相同数目的黑色节点
红黑树添加节点的默认颜色:添加节点时,默认为红色,效率高
保持红黑规则:
根节点位置:直接变为黑色
非根节点位置
父节点为黑色
父节点为红色
叔叔节点为红色
将“父节点”设为黑色,将“叔叔节点”设为黑色
将“祖父节点”设为红色
如果“祖父节点”为根节点,则将根节点再次变成黑色
叔叔节点为黑色(当前节点是父的右孩子)
叔叔节点为黑色(当前节点是父的左孩子)
将“父节点”设为黑色
将“祖父节点”设为红色
以“祖父节点”为支点进行右旋转
Set 无序、不重复、无索引
不可以存储重复元素
没有索引,不能使用普通for循环遍历
1 2 3 4 5 6 7 8 9 10 11 12 Set<String> set = new TreeSet <>(); set.add("aaa" ); Iterator<String> it = set.iterator(); while (it.hasNext()){ String s = it.next(); System.out.println(s); } for (String s : set) { System.out.println(s); }
HashSet:无序、不重复、无索引
LinkedHashSet:有序(存储和取出的元素顺利一致)、不重复、无索引
TreeSet:可排序、不重复、无索引
TreeSet():根据其元素的自然排序进行排序
TreeSet(Comparator comparator):根据指定的比较器进行排序
HashSet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Override public boolean equals (Object o) {}@Override public int hashCode () { return Objects.hash(color, age); }
TreeSet TreeSet():根据其元素的自然排序进行排序
TreeSet(Comparator comparator):根据指定的比较器进行排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 public class Student implements Comparable <Student>{ private String name; private int age; public Student (String name, int age) { this .name = name; this .age = age; } public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } @Override public int compareTo (Student o) { int result = this .age - o.age; result = result == 0 ? this .name.compareTo(o.getName()) : result; return result; } } TreeSet<Student> ts = new TreeSet <>(); Student s1 = new Student ("zhangsan" ,28 );Student s2 = new Student ("lisi" ,27 );public class Teacher { private String name; private int age; public Teacher () { } public Teacher (String name, int age) { this .name = name; this .age = age; } public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } } TreeSet<Teacher> teacherSet = new TreeSet <>(new Comparator <Teacher>() { @Override public int compare (Teacher o1, Teacher o2) { int result = o1.getAge() - o2.getAge(); result = result == 0 ? o1.getName().compareTo(o2.getName()) : result; return result; } });
Map
双列集合,一个键对应一个值
键不可以重复,值可以重复
方法名
说明
V put(K key,V value)
添加元素
V remove(Object key)
根据键删除键值对元素
void clear()
移除所有的键值对元素
boolean containsKey(Object key)
判断集合是否包含指定的键
boolean containsValue(Object value)
判断集合是否包含指定的值
boolean isEmpty()
判断集合是否为空
int size()
集合的长度,也就是集合中键值对的个数
获取功能
方法名
说明
V get(Object key)
根据键获取值
Set keySet()
获取所有键的集合
Collection values()
获取所有值的集合
Set<Map.Entry<K,V>> entrySet()
获取所有键值对对象的集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 Map<String,String> map = new HashMap <String,String>(); map.put("张无忌" , "赵敏1" ); map.put("郭靖" , "黄蓉" ); map.put("杨过" , "小龙女" ); Collection<String> values = map.values(); for (String value : values) { System.out.println(value); } Set<String> keySet = map.keySet(); for (String key : keySet) { String value = map.get(key); System.out.println(key + "," + value); } Set<Map.Entry<String, String>> entrySet = map.entrySet(); for (Map.Entry<String, String> me : entrySet) { String key = me.getKey(); String value = me.getValue(); System.out.println(key + "," + value); } map.forEach((key, value) -> System.out.println(key + "=" + value));
HashMap
HashMap底层是哈希表结构的
依赖hashCode方法和equals方法保证键的唯一
如果键要存储的是自定义对象,需要重写hashCode和equals方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class Student { private String name; private int age; public Student () {} public Student (String name, int age) { this .name = name; this .age = age; } public String getName () { return name; } public int getAge () { return age; } @Override public boolean equals (Object o) { if (this == o) return true ; if (o == null || getClass() != o.getClass()) return false ; Student student = (Student) o; if (age != student.age) return false ; return name != null ? name.equals(student.name) : student.name == null ; } @Override public int hashCode () { int result = name != null ? name.hashCode() : 0 ; result = 31 * result + age; return result; } } HashMap<Student, String> hm = new HashMap <Student, String>(); Student s1 = new Student ("林青霞" , 30 );Set<Student> keySet = hm.keySet(); for (Student key : keySet) { String value = hm.get(key); System.out.println(key.getName() + "," + key.getAge() + "," + value); }
LinkedHashMap 由键决定:有序、不重复、无索引。
这里的有序指的是保证存储和取出的元素顺序一致
TreeMap
TreeMap底层是红黑树结构
依赖自然排序或者比较器排序,对键进行排序
如果键存储的是自定义对象,需要实现Comparable接口或者在创建TreeMap对象时候给出比较器排序规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Student implements Comparable <Student>{ @Override public int compareTo (Student o) { int result = o.getAge() - this .getAge(); result = result == 0 ? o.getName().compareTo(this .getName()) : result; return result; } } TreeMap<Student,String> tm = new TreeMap <>(); tm.forEach( (Student key, String value)->{ System.out.println(key + "---" + value); } );
可变参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 void f (String s, int ... nums) { for (int n : nums) { ... } } f("a" ); f("a" , 1 , 2 , 3 ); f("a" , new int []{1 , 2 });
Collections类
java.utils.Collections 是集合工具类,用来对集合进行操作。
常用方法如下:
public static void shuffle(List<?> list) :打乱集合顺序。
public static <T> void sort(List<T> list) :将集合中元素按照默认规则排序。
public static <T> void sort(List<T> list,Comparator<? super T> ) :将集合中元素按照指定规则排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 public class CollectionsDemo { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList <Integer>(); list.add(100 ); list.add(300 ); list.add(200 ); list.add(50 ); Collections.sort(list); System.out.println(list); } } public class Student { private String name; private int age; } public class Demo { public static void main (String[] args) { ArrayList<Student> list = new ArrayList <Student>(); list.add(new Student ("rose" ,18 )); list.add(new Student ("jack" ,16 )); list.add(new Student ("abc" ,20 )); Collections.sort(list, new Comparator <Student>() { @Override public int compare (Student o1, Student o2) { return o1.getAge()-o2.getAge(); } }); for (Student student : list) { System.out.println(student); } } } Student{name='jack' , age=16 } Student{name='rose' , age=18 } Student{name='abc' , age=20 }
不可变集合 是一个长度不可变,内容也无法修改的集合,只能进行查询操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 List<String> list = List.of("张三" , "李四" , "王五" , "赵六" ); Set<String> set = Set.of("张三" , "张三" , "李四" , "王五" , "赵六" ); Map<String, String> map = Map.of("张三" , "南京" , "张三" , "北京" ); HashMap<String, String> hm = new HashMap <>(); hm.put("张三" , "南京" ); hm.put("陈二" , "嘉兴" ); Map<String, String> immutableMap = Map.copyOf(hm);
Stream流
中间方法:一次操作完毕之后,还可以继续进行其他操作
终结方法:一个Stream流只能有一个终结方法,是流水线上的最后一个操作
生成Stream流的方式
Collection体系集合:使用默认方法stream()生成流, default Stream stream()
Map体系集合:把Map转成Set集合,间接的生成流
数组:通过Arrays中的静态方法stream生成流
同种数据类型的多个数据:通过Stream接口的静态方法of(T… values)生成流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 List<String> list = new ArrayList <String>(); Stream<String> listStream = list.stream(); Set<String> set = new HashSet <String>(); Stream<String> setStream = set.stream(); Map<String,Integer> map = new HashMap <String, Integer>(); Stream<String> keyStream = map.keySet().stream(); Stream<Integer> valueStream = map.values().stream(); Stream<Map.Entry<String, Integer>> entryStream = map.entrySet().stream(); String[] strArray = {"hello" ,"world" ,"java" }; Stream<String> strArrayStream = Arrays.stream(strArray); Stream<String> strArrayStream2 = Stream.of("hello" , "world" , "java" ); Stream<Integer> intStream = Stream.of(10 , 20 , 30 ); int arr1 = {1 , 2 , 3 };String arr2 = {"a" , "b" , "c" }Stream.of(arr1).forEach(s-> System.out.println(s));
中间方法
方法名
说明
Stream filter(Predicate predicate)
用于对流中的数据进行过滤
Stream limit(long maxSize)
返回此流中的元素组成的流,截取前指定参数个数的数据
Stream skip(long n)
跳过指定参数个数的数据,返回由该流的剩余元素组成的流
static Stream concat(Stream a, Stream b)
合并a和b两个流为一个流
Stream distinct()
返回由该流的不同元素(根据 Object.equals(Object) )组成的流
Stream Map(Function<T,R> mapper)
转换流中的数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ArrayList<String> list = new ArrayList <>(); list.add("张三丰" ); list.add("张无忌" ); list.add("王祖贤" ); list.stream().filter(s ->s.startsWith("张" )).forEach(s-> System.out.println(s)); list.stream().limit(3 ).forEach(s-> System.out.println(s)); System.out.println("--------" ); list.stream().skip(3 ).forEach(s-> System.out.println(s)); System.out.println("--------" ); list.stream().skip(2 ).limit(2 ).forEach(s-> System.out.println(s)); Stream<String> s1 = list.stream().limit(4 ); Stream<String> s2 = list.stream().skip(2 ); Stream.concat(s1,s2).distinct().forEach(s-> System.out.println(s)); ArrayList<String> strList = new ArrayList <>(); Collections.addAll(strList, "a-1" , "b-2" ); strList.stream().map(s -> Integer.parseInt(s.split("-" )[1 ]));
终结方法
方法名
说明
void forEach(Consumer action)
对此流的每个元素执行操作
long count()
返回此流中的元素数
Object[] toArray()
返回包含此流元素的数组
1 2 3 4 5 6 7 8 9 long count = list.stream().count();list.stream().forEach(s -> System.out.println(s)); Object[] arr1 = list.stream().toArray(); String[] arr2 = list.stream().toArray(value -> new String [value]);
收集方法
方法名
说明
R collect(Collector collector)
把结果收集到集合中
工具类Collectors提供了具体的收集方式
方法名
说明
public static Collector toList()
把元素收集到List集合中
public static Collector toSet()
把元素收集到Set集合中
public static Collector toMap(Function keyMapper,Function valueMapper)
把元素收集到Map集合中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 List<Integer> list1 = new ArrayList <>(List.of(1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 10 , 10 , 10 , 10 , 10 )); List<Integer> evenList = list1.stream() .filter(number -> number % 2 == 0 ) .collect(Collectors.toList()); Set<Integer> evenSet = list1.stream() .filter(number -> number % 2 == 0 ) .collect(Collectors.toSet()); List<String> list2 = new ArrayList <>(List.of("zhangsan,23" , "lisi,24" , "wangwu,25" )); Map<String, Integer> ageMap = list2.stream() .filter(s -> Integer.parseInt(s.split("," )[1 ]) >= 24 ) .collect(Collectors.toMap( s -> s.split("," )[0 ], s -> Integer.parseInt(s.split("," )[1 ]) ));
方法引用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 public class FunctionDemo1 { public static void main (String[] args) { Integer[] arr = {3 , 5 , 4 , 1 , 6 , 2 }; Arrays.sort(arr, FunctionDemo1::subtraction); } public static int subtraction (int num1, int num2) { return num2 - num1; } } ArrayList<String> list = new ArrayList <>(); Collections.addAll(list,"1" ,"2" ,"3" ,"4" ,"5" ); list.stream().map(Integer::parseInt).forEach(s-> System.out.println(s)); public class StringOperation { public boolean stringJudge (String s) { return s.startsWith("张" ) && s.length() == 3 ; } } public class FunctionDemo3 { public static void main (String[] args) { ArrayList<String> list = new ArrayList <>(); Collections.addAll(list,"张无忌" ,"周芷若" ,"赵敏" ,"张强" ,"张三丰" ); list.stream().filter(new FunctionDemo3 ()::stringJudge).forEach(s-> System.out.println(s)); list.stream().filter(new FunctionDemo3 ()::stringJudge).forEach(s-> System.out.println(s)); public class StringOperation {...} } } public class Student { private String name; private int age; public Student (String str) { String[] arr = str.split("," ); this .name = arr[0 ]; this .age = Integer.parseInt(arr[1 ]); } } List<Student> newList2 = list.stream().map(Student::new ).collect(Collectors.toList()); list.stream().map(String::toUpperCase).forEach(s -> System.out.println(s)); ArrayList<Integer> numList = new ArrayList <>(); Collections.addAll(numList, 1 , 2 , 3 , 4 , 5 ); Integer[] arr2 = numList.stream().toArray(Integer[]::new );
异常 Throwable体系:
Error :严重错误Error,无法通过处理的错误,只能事先避免。
Exception :表示异常,异常产生后程序员可以通过代码的方式纠正,使程序继续运行,是必须要处理的。
异常(Exception)的分类 :根据在编译时期还是运行时期去检查异常?
编译时期异常 :checked异常。在编译时期,就会检查,如果没有处理异常,则编译失败。(如日期格式化异常)
运行时期异常 :runtime异常。在运行时期,检查异常.在编译时期,运行异常不会编译器检测(不报错)。(如数学异常)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 public static void main (String[] args) throws ParseException { *String time = "2030年1月1日" ; SimpleDateFormat sdf = new SimpleDateFormat ("yyyy年MM月dd日" ); Date date = sdf.parse(time); System.out.println(date); } int [] arr = {1 ,2 ,3 ,4 ,5 };System.out.println(arr[10 ]); throw new RuntimeException ();throw new NullPointerException ("要访问的arr数组不存在" );throw new ArrayIndexOutOfBoundsException ("该索引在数组中不存在,已超出范围" );int [] arr = {1 , 2 , 3 , 4 , 5 };try { System.out.println(arr[5 ]); System.out.println(2 /0 ); String s = null ; System.out.println(s.equals("abc" )); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组索引越界" ); } catch (NullPointerException | ArithmeticException e){ System.out.println("索引越界了" ); } catch (Exception e){ System.out.println("Exception" ); } finally { System.out.println("不管程序怎样,这里都将会被执行。" ); }
异常方法
public String getMessage():获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。
public String toString():获取异常的类型和异常描述信息(不用)。
public void printStackTrace():打印异常的跟踪栈信息并输出到控制台
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public static void main (String[] args) throws FileNotFoundException { read("a.txt" ); } public class LoginException extends Exception { public LoginException () {} public LoginException (String message) { super (message); } }
File类
public File(String pathname):通过将给定的路径名字符串 转换为抽象路径名来创建新的 File实例。
public File(String parent, String child):从父路径名字符串和子路径名字符串 创建新的 File实例。
public File(File parent, String child):从父抽象路径名和子路径名字符串 创建新的 File实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 String pathname = "D:\\aaa.txt" ;File file1 = new File (pathname); String pathname2 = "D:\\aaa\\bbb.txt" ;File file2 = new File (pathname2); String parent = "d:\\aaa" ;String child = "bbb.txt" ;File file3 = new File (parent, child);File parentDir = new File ("d:\\aaa" );String child = "bbb.txt" ;File file4 = new File (parentDir, child);
常用方法
public String getAbsolutePath() :返回此File的绝对路径名字符串。
public String getPath() :将此File转换为路径名字符串。
public String getName() :返回由此File表示的文件或目录的名称。
public long length() :返回由此File表示的文件的长度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class FileGet { public static void main (String[] args) { File f = new File ("d:/aaa/bbb.java" ); System.out.println("文件绝对路径:" +f.getAbsolutePath()); System.out.println("文件构造路径:" +f.getPath()); System.out.println("文件名称:" +f.getName()); System.out.println("文件长度:" +f.length()+"字节" ); File f2 = new File ("d:/aaa" ); System.out.println("目录绝对路径:" +f2.getAbsolutePath()); System.out.println("目录构造路径:" +f2.getPath()); System.out.println("目录名称:" +f2.getName()); System.out.println("目录长度:" +f2.length()); } }
绝对路径和相对路径
绝对路径 :从盘符开始的路径,这是一个完整的路径。
相对路径 :相对于项目目录的路径,这是一个便捷的路径,开发中经常使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class FilePath { public static void main (String[] args) { File f = new File ("D:\\bbb.java" ); System.out.println(f.getAbsolutePath()); File f2 = new File ("bbb.java" ); System.out.println(f2.getAbsolutePath()); } } 输出结果: D:\bbb.java D:\idea_project_test4\bbb.java
判断功能的方法
public boolean exists() :此File表示的文件或目录是否实际存在。
public boolean isDirectory() :此File表示的是否为目录。
public boolean isFile() :此File表示的是否为文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class FileIs { public static void main (String[] args) { File f = new File ("d:\\aaa\\bbb.java" ); File f2 = new File ("d:\\aaa" ); System.out.println("d:\\aaa\\bbb.java 是否存在:" +f.exists()); System.out.println("d:\\aaa 是否存在:" +f2.exists()); System.out.println("d:\\aaa 文件?:" +f2.isFile()); System.out.println("d:\\aaa 目录?:" +f2.isDirectory()); } } 输出结果: d:\aaa\bbb.java 是否存在:true d:\aaa 是否存在:true d:\aaa 文件?:false d:\aaa 目录?:true
创建删除功能的方法
public boolean createNewFile() :当且仅当具有该名称的文件尚不存在时,创建一个新的空文件。
public boolean delete() :删除由此File表示的文件或目录。
public boolean mkdir() :创建由此File表示的目录。
public boolean mkdirs() :创建由此File表示的目录,包括任何必需但不存在的父目录。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class FileCreateDelete { public static void main (String[] args) throws IOException { File f = new File ("aaa.txt" ); System.out.println("是否存在:" +f.exists()); System.out.println("是否创建:" +f.createNewFile()); System.out.println("是否存在:" +f.exists()); File f2= new File ("newDir" ); System.out.println("是否存在:" +f2.exists()); System.out.println("是否创建:" +f2.mkdir()); System.out.println("是否存在:" +f2.exists()); File f3= new File ("newDira\\newDirb" ); System.out.println(f3.mkdir()); File f4= new File ("newDira\\newDirb" ); System.out.println(f4.mkdirs()); System.out.println(f.delete()); System.out.println(f2.delete()); System.out.println(f4.delete()); } }
目录的遍历
public String[] list() :返回一个String数组,表示该File目录中的所有子文件或目录。
public File[] listFiles() :返回一个File数组,表示该File目录中的所有的子文件或目录。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class FileFor { public static void main (String[] args) { File dir = new File ("d:\\java_code" ); String[] names = dir.list(); for (String name : names){ System.out.println(name); } File[] files = dir.listFiles(); for (File file : files) { System.out.println(file); } } }
IO IO的分类 根据数据的流向分为:输入流 和输出流 。
输入流 :把数据从其他设备上读取到内存中的流。
输出流 :把数据从内存 中写出到其他设备上的流。
格局数据的类型分为:字节流 和字符流 。
字节流 :以字节为单位,读写数据的流。(一切文件数据)
字符流 :以字符为单位,读写数据的流。(文本)
输入流
输出流
字节流
字节输入流 InputStream
字节输出流 OutputStream
字符流
字符输入流 Reader
字符输出流 Writer
字节流 字节输出流
java.io.OutputStream 抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。
public void close() :关闭此输出流并释放与此流相关联的任何系统资源。
public void flush() :刷新此输出流并强制任何缓冲的输出字节被写出。
public void write(byte[] b):将 b.length字节从指定的字节数组写入此输出流。
public void write(byte[] b, int off, int len) :从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。
public abstract void write(int b) :将指定的字节输出流。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 File file = new File ("a.txt" );FileOutputStream fos = new FileOutputStream (file); FileOutputStream fos = new FileOutputStream ("b.txt" ); fos.write(97 ); fos.write(98 ); byte [] b = "黑马程序员" .getBytes();fos.write(b); byte [] c = "abcde" .getBytes();fos.write(c,2 ,2 ); fos.close(); FileOutputStream fos = new FileOutputStream ("fos.txt" ,true ); byte [] b = "abcde" .getBytes();fos.write(b); byte [] words = {97 ,98 ,99 ,100 ,101 };for (int i = 0 ; i < words.length; i++) { fos.write(words[i]); fos.write("\r\n" .getBytes()); } fos.close();
字节输入流
java.io.InputStream 抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。它定义了字节输入流的基本共性功能方法。
public void close() :关闭此输入流并释放与此流相关联的任何系统资源。
public abstract int read(): 从输入流读取数据的下一个字节。
public int read(byte[] b): 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 File file = new File ("a.txt" );FileInputStream fos = new FileInputStream (file);FileInputStream fis = new FileInputStream ("read.txt" );int read = fis.read();System.out.println((char ) read); read = fis.read(); System.out.println((char ) read); read = fis.read(); read = fis.read(); System.out.println( read); fis.close(); int b;while ((b = fis.read())!=-1 ) { System.out.println((char )b); } fis.close(); FileInputStream fis = new FileInputStream ("read.txt" ); int len ;byte [] b = new byte [2 ];while (( len= fis.read(b))!=-1 ) { System.out.println(new String (b,0 ,len)); } fis.close();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 FileInputStream fis = new FileInputStream ("D:\\itheima\\movie.mp4" );FileOutputStream fos = new FileOutputStream ("myio\\copy.mp4" );int len;byte [] bytes = new byte [1024 * 1024 * 5 ];while ((len = fis.read(bytes)) != -1 ){ fos.write(bytes,0 ,len); } fos.close(); fis.close(); public class HandleException2 { public static void main (String[] args) { try ( FileWriter fw = new FileWriter ("fw.txt" ); ) { fw.write("黑马程序员" ); } catch (IOException e) { e.printStackTrace(); } } } public class TryDemo { public static void main (String[] args) throws IOException { final FileReader fr = new FileReader ("in.txt" ); FileWriter fw = new FileWriter ("out.txt" ); try (fr; fw) { int b; while ((b = fr.read())!=-1 ) { fw.write(b); } } catch (IOException e) { e.printStackTrace(); } } }
编码和解码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 String str = "ai你哟" ;byte [] bytes1 = str.getBytes();System.out.println(Arrays.toString(bytes1)); byte [] bytes2 = str.getBytes("GBK" );System.out.println(Arrays.toString(bytes2)); String str2 = new String (bytes1);System.out.println(str2); String str3 = new String (bytes1,"GBK" );System.out.println(str3);
字符流 输入流
java.io.Reader 是字符输入流的超类,用于读取字符信息到内存。
核心方法:
close():关闭流并释放资源。
read():读取一个字符,返回 int,末尾返回 -1。
read(char[] cbuf):读取多个字符到数组,返回有效字符数,末尾返回 -1。
FileReader:读取字符文件的便利类。
构造:new FileReader(File file) 或 new FileReader(String fileName)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 try (Reader fr = new FileReader ("read.txt" )) { char [] buf = new char [2 ]; int len; while ((len = fr.read(buf)) != -1 ) { System.out.print(new String (buf, 0 , len)); } } int len;char [] cbuf = new char [2 ];while ((len = fr.read(cbuf))!=-1 ) { System.out.println(new String (cbuf,0 ,len)); }
输出流
java.io.Writer 是字符输出流的超类,用于写出字符信息到目的地。
write(int c):写一个字符。
write(char[] cbuf):写字符数组。
write(char[] cbuf, int off, int len):写字符数组一部分。
write(String str):写字符串。
write(String str, int off, int len):写字符串一部分。
flush():刷新缓冲,流可继续使用。
close():先刷新,再释放资源,之后不能再用。
FileWriter:写出字符到文件的便利类。
构造:new FileWriter(File/String) 默认清空;new FileWriter(File/String, true) 追加数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 fw.write(97 ); fw.write('b' ); fw.write('C' ); fw.write(30000 ); fw.close(); fw.flush(); char [] chars = "黑马程序员" .toCharArray();fw.write(chars); String msg = "黑马程序员" ;fw.write(msg); fw.write(msg,2 ,2 );
缓冲流
字节缓冲流:BufferedInputStream,BufferedOutputStream
字符缓冲流:BufferedReader,BufferedWriter
字节缓冲流
public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流。
public BufferedOutputStream(OutputStream out): 创建一个新的缓冲输出流。
1 2 3 4 BufferedInputStream bis = new BufferedInputStream (new FileInputStream ("bis.txt" ));BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream ("bos.txt" ));
字符缓冲流
public BufferedReader(Reader in) :创建一个 新的缓冲输入流。
public BufferedWriter(Writer out): 创建一个新的缓冲输出流。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 BufferedReader br = new BufferedReader (new FileReader ("br.txt" ));BufferedWriter bw = new BufferedWriter (new FileWriter ("bw.txt" ));String line = null ;while ((line = br.readLine())!=null ) { System.out.print(line); } bw.write("黑马" ); bw.newLine();
转换流 转换流:是 Reader、Writer 的子类,是从字节流到字符流的桥梁。Reader 它读取字节并使用指定的字符集将其解码为字符。Writer 使用指定的字符集将字符编码为字节。字符集可以由名称指定,也可以接受平台的默认字符集。
InputStreamReader(InputStream in): 创建一个使用默认字符集的字符流。
InputStreamReader(InputStream in, String charsetName): 创建一个指定字符集的字符流。
OutputStreamWriter(OutputStream in): 创建一个使用默认字符集的字符流。
OutputStreamWriter(OutputStream in, String charsetName): 创建一个指定字符集的字符流。
1 2 3 4 5 6 7 8 9 10 11 12 InputStreamReader isr = new InputStreamReader (new FileInputStream ("in.txt" ));InputStreamReader isr2 = new InputStreamReader (new FileInputStream ("in.txt" ) , "GBK" );FileReader fr = new FileReader ("myio\\gbkfile.txt" , Charset.forName("GBK" ));OutputStreamWriter isr = new OutputStreamWriter (new FileOutputStream ("out.txt" ));OutputStreamWriter isr2 = new OutputStreamWriter (new FileOutputStream ("out.txt" ) , "GBK" );FileWriter fw = new FileWriter ("myio\\c.txt" , Charset.forName("GBK" ));BufferedReader br = new BufferedReader (new InputStreamReader (new FileInputStream ("myio\\a.txt" )));br.readLine();
序列化 java.io.ObjectOutputStream 序列化类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。
java.io.ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public class Employee implements java .io.Serializable { public String name; public String address; public transient int age; public void addressCheck () { System.out.println("Address check : " + name + " -- " + address); } } Employee e = new Employee ();ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("employee.txt" ));out.writeObject(e); Employee e = null ;try { ObjectInputStream in = new ObjectInputStream (new FileInputStream ("employee.txt" )); e = (Employee) in.readObject(); } catch (ClassNotFoundException c) { c.printStackTrace(); return ; } private static final long serialVersionUID = 1L ;
打印流 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 PrintStream ps = new PrintStream ("ps.txt" );public class PrintStreamDemo { public static void main (String[] args) throws FileNotFoundException { PrintStream ps = new PrintStream (new FileOutputStream ("myio\\a.txt" ), true , Charset.forName("UTF-8" )); ps.println(97 ); ps.print(true ); ps.println(); ps.printf("%s爱上了%s" ,"阿珍" ,"阿强" ); ps.close(); } } System.out.println(97 ); PrintStream ps = new PrintStream ("ps.txt" );System.setOut(ps); System.out.println(97 ); PrintWriter pw = new PrintWriter (new FileWriter ("myio\\a.txt" ),true );pw.println("测试1" ); pw.print("测试2" ); pw.printf("测试3" ); pw.close();
压缩流 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 import java.io.*;import java.nio.file.*;import java.util.zip.*;public class ZipUtil { public static void unzip (File src, File dest) throws IOException { try (ZipInputStream zip = new ZipInputStream (new FileInputStream (src))) { ZipEntry entry; while ((entry = zip.getNextEntry()) != null ) { File out = new File (dest, entry.getName()); if (entry.isDirectory()) { out.mkdirs(); } else { out.getParentFile().mkdirs(); Files.copy(zip, out.toPath(), StandardCopyOption.REPLACE_EXISTING); } } } } public static void zipFile (File src, File destZip) throws IOException { try (ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (destZip)); FileInputStream fis = new FileInputStream (src)) { zos.putNextEntry(new ZipEntry (src.getName())); fis.transferTo(zos); zos.closeEntry(); } } public static void zipDir (File src, File destZip) throws IOException { try (ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (destZip))) { addToZip(src, zos, src.getName()); } } private static void addToZip (File dir, ZipOutputStream zos, String name) throws IOException { File[] files = dir.listFiles(); if (files == null ) return ; for (File file : files) { String entryName = name + "/" + file.getName(); if (file.isFile()) { zos.putNextEntry(new ZipEntry (entryName)); try (FileInputStream fis = new FileInputStream (file)) { fis.transferTo(zos); } zos.closeEntry(); } else { addToZip(file, zos, entryName); } } } public static void main (String[] args) throws IOException { unzip(new File ("D:/aaa.zip" ), new File ("D:/out" )); zipFile(new File ("D:/a.txt" ), new File ("D:/a.zip" )); File src = new File ("D:/aaa" ); zipDir(src, new File (src.getParentFile(), src.getName() + ".zip" )); } }
工具包 Commons-io、hutool
使用方式:
1,新建lib文件夹
2,把第三方jar包粘贴到文件夹中
3,右键点击 add as a library
多线程
并行:在同一时刻,有多个指令在多个CPU上同时执行。
并发:在同一时刻,有多个指令在单个CPU上交替执行。
实现多线程方式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 public class MyThread extends Thread { @Override public void run () { for (int i=0 ; i<100 ; i++) { System.out.println(i); } } } public class MyThreadDemo { public static void main (String[] args) { MyThread my1 = new MyThread (); my1.start(); } } public class MyRunnable implements Runnable { @Override public void run () { for (int i=0 ; i<100 ; i++) { System.out.println(Thread.currentThread().getName()+":" +i); } } } public class MyRunnableDemo { public static void main (String[] args) { MyRunnable my = new MyRunnable (); Thread t1 = new Thread (my,"坦克" ); t1.start(); } } public class MyCallable implements Callable <String> { @Override public String call () throws Exception { for (int i = 0 ; i < 100 ; i++) { System.out.println("跟女孩表白" + i); } return "答应" ; } } public class Demo { public static void main (String[] args) throws ExecutionException, InterruptedException { MyCallable mc = new MyCallable (); FutureTask<String> ft = new FutureTask <>(mc); Thread t1 = new Thread (ft); t1.start(); String s = ft.get(); System.out.println(s); } }
设置和获取线程名称
常用方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class MyThreadNotes extends Thread { String name = getName(); setName("我的线程" ); Thread t = Thread.currentThread(); Thread.sleep(1000 ); Thread.yield (); setPriority(10 ); int p = getPriority(); setDaemon(true ); join(); }
线程同步 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public class SellTicket implements Runnable { private int tickets = 100 ; private Object obj = new Object (); @Override public void run () { while (true ) { synchronized (obj) { if (tickets > 0 ) { try { Thread.sleep(100 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票" ); tickets--; } } } } } private static synchronized boolean synchronizedMthod () {}
Lock锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package com.itheima.a11threadsafe3;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class MyThread extends Thread { static int ticket = 0 ; static Lock lock = new ReentrantLock (); @Override public void run () { while (true ){ lock.lock(); try { if (ticket == 100 ){ break ; }else { Thread.sleep(10 ); ticket++; } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }
死锁
线程死锁是指由于两个或者多个线程互相持有对方所需要的资源,导致这些线程处于等待状态,无法前往执行
什么情况下会产生死锁:1.资源有限 2.同步嵌套
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class Demo { public static void main (String[] args) { Object objA = new Object (); Object objB = new Object (); new Thread (()->{ while (true ){ synchronized (objA){ synchronized (objB){ System.out.println("小康同学正在走路" ); } } } }).start(); new Thread (()->{ while (true ){ synchronized (objB){ synchronized (objA){ System.out.println("小薇同学正在走路" ); } } } }).start(); } }
生产者消费者
方法名
说明
void wait()
导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法
void notify()
唤醒正在等待对象监视器的单个线程
void notifyAll()
唤醒正在等待对象监视器的所有线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 public class Desk { public static boolean flag = false ; public static int count = 10 ; public static final Object lock = new Object (); } public class Cooker extends Thread { @Override public void run () { while (true ){ synchronized (Desk.lock){ if (Desk.count == 0 ){ break ; }else { if (!Desk.flag){ System.out.println("厨师正在生产汉堡包" ); Desk.flag = true ; Desk.lock.notifyAll(); }else { try { Desk.lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } } public class Foodie extends Thread { @Override public void run () { while (true ){ synchronized (Desk.lock){ if (Desk.count == 0 ){ break ; }else { if (Desk.flag){ System.out.println("吃货在吃汉堡包" ); Desk.flag = false ; Desk.lock.notifyAll(); Desk.count--; }else { try { Desk.lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } } public class Demo { public static void main (String[] args) { Foodie f = new Foodie (); Cooker c = new Cooker (); f.start(); c.start(); } }
阻塞队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 public class Cooker extends Thread { private ArrayBlockingQueue<String> bd; public Cooker (ArrayBlockingQueue<String> bd) { this .bd = bd; } @Override public void run () { while (true ) { try { bd.put("汉堡包" ); System.out.println("厨师放入一个汉堡包" ); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Foodie extends Thread { private ArrayBlockingQueue<String> bd; public Foodie (ArrayBlockingQueue<String> bd) { this .bd = bd; } @Override public void run () { while (true ) { try { String take = bd.take(); System.out.println("吃货将" + take + "拿出来吃了" ); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Demo { public static void main (String[] args) { ArrayBlockingQueue<String> bd = new ArrayBlockingQueue <>(1 ); Foodie f = new Foodie (bd); Cooker c = new Cooker (bd); f.start(); c.start(); } }
线程池 线程池是线程复用与任务调度机制,通过预先管理一组工作线程和任务队列,避免频繁创建、销毁线程,并控制并发规模。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 ExecutorService pool1 = Executors.newFixedThreadPool(3 );pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); pool1.submit(new MyRunnable ()); ThreadPoolExecutor pool = new ThreadPoolExecutor ( 3 , 6 , 60 , TimeUnit.SECONDS, new ArrayBlockingQueue <>(3 ), Executors.defaultThreadFactory(), new ThreadPoolExecutor .AbortPolicy() ); int count = Runtime.getRuntime().availableProcessors();System.out.println(count);
网络编程 三要素:IP地址、端口、协议
IP地址
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class InetAddressDemo { public static void main (String[] args) throws UnknownHostException { InetAddress address = InetAddress.getByName("192.168.1.66" ); String name = address.getHostName(); String ip = address.getHostAddress(); System.out.println("主机名:" + name); System.out.println("IP地址:" + ip); } }
端口: 用两个字节表示的整数,它的取值范围是065535。其中,01023之间的端口号用于一些知名的网络服务和应用,普通的应用程序需要使用1024以上的端口号
UDP协议 :
用户数据报协议(User Datagram Protocol)
UDP是面向无连接通信协议。速度快,有大小限制一次最多发送64K,数据不安全,易丢失数据
TCP协议:
传输控制协议 (Transmission Control Protocol)
TCP是面向连接通信协议。速度慢,没有大小限制,数据安全。
UDP通信程序 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 DatagramSocket ds = new DatagramSocket ();byte [] bytes = "你好!" .getBytes();DatagramPacket dp = new DatagramPacket (bytes, bytes.length, InetAddress.getByName("127.0.0.1" ), 10086 );ds.send(dp); ds.close(); DatagramSocket ds = new DatagramSocket (10086 );byte [] bytes = new byte [1024 ];DatagramPacket dp = new DatagramPacket (bytes,bytes.length);ds.receive(dp); byte [] data = dp.getData();int len = dp.getLength();InetAddress address = dp.getAddress();int port = dp.getPort();System.out.println("接收到数据" + new String (data,0 ,len)); System.out.println("该数据是从" + address + "这台电脑中的" + port + "这个端口发出的" ); ds.close(); MulticastSocket ms = new MulticastSocket (); InetAddress address = InetAddress.getByName("224.0.0.1" );MulticastSocket ms = new MulticastSocket (10000 );InetAddress address = InetAddress.getByName("224.0.0.1" );ms.joinGroup(address); DatagramSocket ds = new DatagramSocket ();InetAddress address = InetAddress.getByName("255.255.255.255" );
TCP通信 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Socket socket = new Socket ("127.0.0.1" ,10000 );OutputStream os = socket.getOutputStream();os.write("aaa" .getBytes()); os.close(); socket.close(); ServerSocket ss = new ServerSocket (10000 );Socket socket = ss.accept();InputStream is = socket.getInputStream();int b;while ((b = is.read()) != -1 ){ System.out.println((char ) b); } socket.close(); ss.close();
反射
利用反射 创建的对象可以无视修饰符 调用类里面的内容
可以跟配置文件结合起来使用 ,把要创建的对象信息和方法写在配置文件中。(读取到什么类,就创建什么类的对象。读取到什么方法,就调用什么方法。此时当需求变更的时候不需要修改代码,只要修改配置文件即可)
获取字节码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Class clazz1 = Class.forName("com.itheima.reflectdemo.Student" );Class clazz2 = Student.class;System.out.println(clazz1 == clazz2); Student s = new Student ();Class clazz3 = s.getClass();System.out.println(clazz1 == clazz2); System.out.println(clazz2 == clazz3);
获取构造方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public class ReflectDemo2 { public static void main (String[] args) throws ClassNotFoundException, NoSuchMethodException { Class clazz = Class.forName("com.itheima.reflectdemo.Student" ); Constructor[] constructors1 = clazz.getConstructors(); for (Constructor constructor : constructors1) {} Constructor[] constructors2 = clazz.getDeclaredConstructors(); for (Constructor constructor : constructors2) { System.out.println(constructor); } Constructor con1 = clazz.getConstructor(); Constructor con2 = clazz.getConstructor(String.class,int .class); Constructor con3 = clazz.getDeclaredConstructor(); Constructor con4 = clazz.getDeclaredConstructor(String.class); } } int modifiers = con4.getModifiers();Student stu = (Student) con.newInstance();con.setAccessible(true ); Student stu = (Student) con.newInstance("zhangsan" , 23 );
获取成员变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Class clazz = Class.forName("com.itheima.myreflect3.Student" );Field name = clazz.getDeclaredField("name" );int modifiers = name.getModifiers();String n = name.getName();Class<?> type = name.getType(); Student s = new Student ("zhangsan" ,23 ,"男" );name.setAccessible(true ); String value = (String) name.get(s);name.set(s,"lisi" );
获取成员方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Class clazz = Class.forName("com.itheima.myreflect4.Student" );Method[] methods = clazz.getMethods(); Method[] methods = clazz.getDeclaredMethods(); Method m = clazz.getDeclaredMethod("eat" , String.class);int modifiers = m.getModifiers();String name = m.getName();Parameter[] parameters = m.getParameters(); Class[] exceptionTypes = m.getExceptionTypes(); Student s = new Student ();m.setAccessible(true ); String result = (String) m.invoke(s, "汉堡包" );
动态代理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class ProxyUtil { public static Star createProxy (BigStar bigStar) { Star star = (Star) Proxy.newProxyInstance( ProxyUtil.class.getClassLoader(), new Class []{Star.class}, new InvocationHandler () { @Override public Object invoke (Object proxy, Method method, Object[] args) throws Throwable { if ("sing" .equals(method.getName())){ System.out.println("准备话筒,收钱" ); }else if ("dance" .equals(method.getName())){ System.out.println("准备场地,收钱" ); } return method.invoke(bigStar,args); } } ); return star; } } BigStar bigStar = new BigStar ("鸡哥" );Star proxy = ProxyUtil.createProxy(bigStar);String result = proxy.sing("只因你太美" );
日志 Logback 配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <?xml version="1.0" encoding="UTF-8" ?> <configuration > <appender name ="CONSOLE" class ="ch.qos.logback.core.ConsoleAppender" > <target > System.out</target > <encoder > <pattern > %d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %c [%thread] : %msg%n</pattern > </encoder > </appender > <appender name ="FILE" class ="ch.qos.logback.core.rolling.RollingFileAppender" > <encoder > <pattern > %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern > <charset > utf-8</charset > </encoder > <file > C:/code/itheima-data.log</file > <rollingPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy" > <fileNamePattern > C:/code/itheima-data2-%d{yyyy-MMdd}.log%i.gz</fileNamePattern > <maxFileSize > 1MB</maxFileSize > </rollingPolicy > </appender > <root level ="info" > <appender-ref ref ="CONSOLE" /> <appender-ref ref ="FILE" /> </root > </configuration >
使用
1 2 3 4 5 6 public class Sample { private static final Logger LOGGER = LoggerFactory.getLogger(Sample.class); public static void main (String[] args) { LOGGER.info("A Message From LOGGER:{}" , "Hello World" ); } }
类加载器 1 2 3 4 5 6 7 8 9 10 11 12 ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();ClassLoader classLoader1 = systemClassLoader.getParent();ClassLoader classLoader2 = classLoader1.getParent();InputStream is = systemClassLoader.getResourceAsStream("prop.properties" ); Properties prop = new Properties ();prop.load(is); is.close();
单元测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public class JunitTest { @Test public void method2Test () {} } public class JunitDemo3 { @Before public void beforemethod () throws IOException { File src = new File ("C:\\Users\\moon\\Desktop\\a.txt" ); File dest = new File ("C:\\Users\\moon\\Desktop\\copy.txt" ); FileInputStream fis = new FileInputStream (src); FileOutputStream fos = new FileOutputStream (dest); int b; while ((b = fis.read()) != -1 ){ fos.write(b); } fos.close(); fis.close(); } @Test public void method () { File file = new File ("C:\\Users\\moon\\Desktop\\a.txt" ); boolean delete = file.delete(); boolean exists = file.exists(); Assert.assertEquals("delete方法出错了" ,delete,true ); Assert.assertEquals("delete方法出错了" ,exists,false ); } @After public void aftermethod () throws IOException { File src = new File ("C:\\Users\\moon\\Desktop\\copy.txt" ); File dest = new File ("C:\\Users\\moon\\Desktop\\a.txt" ); FileInputStream fis = new FileInputStream (src); FileOutputStream fos = new FileOutputStream (dest); int b; while ((b = fis.read()) != -1 ){ fos.write(b); } fos.close(); fis.close(); src.delete(); } }
注解