map和一异常

一、遍历Map集合(掌握)

1.1 定义

  • 获取Map集合中所有的键和值
  • 可以通过key来获取
  • 可以通过entry来获取

1.2 通过key获取所有的键值对内容

  • 获取所有的key
    • map.keySet()
  • 遍历keys
    • 使用foreach
    • 使用iterator
package com.qf.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Demo01 {
	public static void main(String[] args) {
		HashMap<String, Stu> stus = new HashMap<String, Stu>();
		stus.put("201602030405", new Stu("贾宝玉", 16));
		stus.put("201602030408", new Stu("林黛玉", 15));
		stus.put("201602030409", new Stu("薛宝钗", 17));
		stus.put("201602030410", new Stu("刘姥姥", 66));
		stus.put("201602030403", new Stu("王熙凤", 26));
		
		System.out.println(stus);
		/**
		 * 	通过key可以获取key对应的value,所以通过所有的key可以获取所有的value
		 * 
		 * 	通过获取所有的键值对,遍历键值对的集合
		 */
		
		/**
		 * 	获取所有的key---keySet
		 * 	遍历所有的key---foreach/iterator
		 * 	通过key来获取key对应的value
		 */
		Set<String> keys = stus.keySet();
		System.out.println("================key-foreach==================");
		for (String id : keys) {
			System.out.println(id + "==" + stus.get(id));
		}
		
		System.out.println("================key-iterator==================");
		Iterator<String> its = keys.iterator();
		while(its.hasNext()) {
			String id = its.next();
			System.out.println(id + "====" + stus.get(id));
		}
	}
}

class Stu{
	private String name;
	private int 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;
	}

	public Stu(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public Stu() {
		super();
	}

	@Override
	public String toString() {
		return "Stu [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Stu other = (Stu) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}

1.3 通过键值对获取所有的键和值

  • 获取所有的键值对
    • map.entrySet()
  • 遍历entrys
    • 使用foreach
    • 使用iterator
  • 获取entry中的键和值
    • entry.getKey()
    • entry.getValue()
package com.qf.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Demo01 {
	public static void main(String[] args) {
		HashMap<String, Stu> stus = new HashMap<String, Stu>();
		stus.put("201602030405", new Stu("贾宝玉", 16));
		stus.put("201602030408", new Stu("林黛玉", 15));
		stus.put("201602030409", new Stu("薛宝钗", 17));
		stus.put("201602030410", new Stu("刘姥姥", 66));
		stus.put("201602030403", new Stu("王熙凤", 26));
		
		System.out.println(stus);
		/**
		 * 	通过key可以获取key对应的value,所以通过所有的key可以获取所有的value
		 * 
		 * 	通过获取所有的键值对,遍历键值对的集合
		 */
		System.out.println("================entry-foreach==================");
		// 获取所有的键值对
		Set<Map.Entry<String,Stu>> entrys = stus.entrySet();
		System.out.println(entrys);
		// 遍历所有的键值对
		for (Map.Entry<String, Stu> entry : entrys) {
			// 输出键值对
			System.out.println(entry);
		}
		
		System.out.println("================entry-foreach==================");
		for (Map.Entry<String, Stu> entry : entrys) {
			// 通过entry的getKey和getValue方法获取键和值
			System.out.println(entry.getKey() + "===" + entry.getValue());
		}
		
		System.out.println("================entry-iterator==================");
		// 使用entrys的iterator方法获取迭代器对象,迭代器对象包含了entrys中的所有内容
		Iterator<Map.Entry<String,Stu>> it = entrys.iterator();
		// 遍历迭代器对象,获取里面的entry
		while(it.hasNext()) {
			// 获取到的entry
			Map.Entry<String, Stu> entry = it.next();
			System.out.println(entry);
		}
		it = entrys.iterator();
		System.out.println("================entry-iterator==================");
		while(it.hasNext()) {
			Map.Entry<String, Stu> entry = it.next();
			System.out.println(entry.getKey() + "====" + entry.getValue());
		}
	}
}

class Stu{
	private String name;
	private int 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;
	}

	public Stu(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public Stu() {
		super();
	}

	@Override
	public String toString() {
		return "Stu [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Stu other = (Stu) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}

二、TreeMap(掌握)

1.1 定义

  • 基于红黑树(Red-Black tree)的 NavigableMap 实现。
  • 该映射根据其键的自然顺序进行排序
  • 或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。

1.2 创建对象

TreeMap() 
          使用键的自然顺序构造一个新的、空的树映射。 
TreeMap(Comparator<? super K> comparator) 
          构造一个新的、空的树映射,该映射根据给定比较器进行排序。 
TreeMap(Map<? extends K,? extends V> m) 
          构造一个与给定映射具有相同映射关系的新的树映射,该映射根据其键的自然顺序 进行排序。 
TreeMap(SortedMap<K,? extends V> m) 
          构造一个与指定有序映射具有相同映射关系和相同排序顺序的新的树映射。 
1.2.1 使用空参方式创建对象
package com.qf.treemap;

import java.util.TreeMap;

public class Demo01 {
	public static void main(String[] args) {
		TreeMap<Integer, String> map = new TreeMap<Integer, String>();
		map.put(10010, "中国联合通讯集团");
		map.put(95595, "中国光大银行");
		map.put(10000, "中国电信集团");
		map.put(10086, "中国移动通讯集团");
		System.out.println(map);
	}
}
1.2.2 使用空参方式创建对象,但是对象实现Comparable接口
package com.qf.treemap;

import java.util.TreeMap;

public class Demo02 {
	public static void main(String[] args) {
		// 创建TreeMap集合,泛型是String、Person
		TreeMap<String, Person> map = new TreeMap<String, Person>();
		map.put("201602030405", new Person(10010, 23, "张三", "南京"));
		map.put("201602030406", new Person(10008, 23, "张三", "南京"));
		map.put("201602030407", new Person(10011, 23, "张三", "南京"));
		map.put("201602030408", new Person(10005, 23, "张三", "南京"));
		map.put("201602030409", new Person(10006, 23, "张三", "南京"));
		System.out.println(map);
		
		// 创建TreeMap集合,泛型是Person、String
		TreeMap<Person, String> persons = new TreeMap<Person, String>();
		persons.put(new Person(10010, 23, "张三", "南京"), "201602030405");
		persons.put(new Person(10008, 22, "张三", "南京"), "201602030405");
		persons.put(new Person(10006, 29, "张三", "南京"), "201602030405");
		persons.put(new Person(10018, 27, "张三", "南京"), "201602030405");
		persons.put(new Person(10012, 21, "张三", "南京"), "201602030405");
		System.out.println(persons);
	}
}

class Person implements Comparable<Person>{
	private int id;
	private int age;
	private String name;
	private String addr;
	
	public Person() {
		super();
	}

	public Person(int id, int age, String name, String addr) {
		super();
		this.id = id;
		this.age = age;
		this.name = name;
		this.addr = addr;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	// 比较的规则
	@Override
	public int compareTo(Person p) {
		int ret = this.id - p.id;
		return ret == 0 ? this.name.compareTo(p.name) : ret;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", age=" + age + ", name=" + name + ", addr=" + addr + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((addr == null) ? 0 : addr.hashCode());
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (addr == null) {
			if (other.addr != null)
				return false;
		} else if (!addr.equals(other.addr))
			return false;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}
1.2.3 使用有参方式创建对象,传入比较器–Comparator引用的实例
package com.qf.treemap;

import java.util.Comparator;
import java.util.TreeMap;

public class Demo03 {
	public static void main(String[] args) {
		// 创建比较器,使用lambda表达式
		Comparator<Human> comparator = (Human h1,Human h2) -> {return h1.getId()-h2.getId();};
		
		// 创建TreeMap集合,泛型是Human、String
		TreeMap<Human, String> map = new TreeMap<Human, String>(comparator);
		
		map.put(new Human(10010, 23, "张三", "南京"), "201602030405");
		map.put(new Human(10008, 25, "李四", "北京"), "201602030408");
		map.put(new Human(10012, 21, "王五", "东京"), "201602030410");
		map.put(new Human(10009, 29, "翟柳", "西京"), "201602030422");
		map.put(new Human(10011, 18, "田七", "中京"), "201602030499");
		
		System.out.println(map);
	}
}

class Human{
	private int id;
	private int age;
	private String name;
	private String addr;
	
	public Human() {
		super();
	}
	
	public Human(int id, int age, String name, String addr) {
		super();
		this.id = id;
		this.age = age;
		this.name = name;
		this.addr = addr;
	}
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getAddr() {
		return addr;
	}
	
	public void setAddr(String addr) {
		this.addr = addr;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((addr == null) ? 0 : addr.hashCode());
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Human other = (Human) obj;
		if (addr == null) {
			if (other.addr != null)
				return false;
		} else if (!addr.equals(other.addr))
			return false;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Human [id=" + id + ", age=" + age + ", name=" + name + ", addr=" + addr + "]";
	}
}

1.3 常用方法

package com.qf.treemap;

public class Demo04 {
	public static void main(String[] args) {
		/**
		 * 方法摘要 
		 * 	增
		 * 	 V put(K key, V value) 
			          将指定值与此映射中的指定键进行关联。 
			 void putAll(Map<? extends K,? extends V> map) 
			          将指定映射中的所有映射关系复制到此映射中。 

			删
			 V remove(Object key) 
			          如果此 TreeMap 中存在该键的映射关系,则将其删除。 
			 void clear() 
			          从此映射中移除所有映射关系。 
			 Map.Entry<K,V> pollFirstEntry() 
				移除并返回与此映射中的最小键关联的键-值映射关系;如果映射为空,则返回 null。 
			 Map.Entry<K,V> pollLastEntry() 
				移除并返回与此映射中的最大键关联的键-值映射关系;如果映射为空,则返回 null。 
				
			改	
		  	 V put(K key, V value) 
			          将指定值与此映射中的指定键进行关联。 
			          
			查         
			 Map.Entry<K,V> ceilingEntry(K key) 
			          返回一个键-值映射关系,它与大于等于给定键的最小键关联;如果不存在这样的键,则返回 null。 
			 K ceilingKey(K key) 
			          返回大于等于给定键的最小键;如果不存在这样的键,则返回 null。 
			 Comparator<? super K> comparator() 
			          返回对此映射中的键进行排序的比较器;如果此映射使用键的自然顺序,则返回 null。 
			 boolean containsKey(Object key) 
			          如果此映射包含指定键的映射关系,则返回 true。 
			 boolean containsValue(Object value) 
			          如果此映射为指定值映射一个或多个键,则返回 true。 
			 Set<Map.Entry<K,V>> entrySet() 
			          返回此映射中包含的映射关系的 Set 视图。 
			 Map.Entry<K,V> firstEntry() 
			          返回一个与此映射中的最小键关联的键-值映射关系;如果映射为空,则返回 null。 
			 K firstKey() 
			          返回此映射中当前第一个(最低)键。 
			 Map.Entry<K,V> floorEntry(K key) 
			          返回一个键-值映射关系,它与小于等于给定键的最大键关联;如果不存在这样的键,则返回 null。 
			 K floorKey(K key) 
			          返回小于等于给定键的最大键;如果不存在这样的键,则返回 null。 
			 V get(Object key) 
			          返回指定键所映射的值,如果对于该键而言,此映射不包含任何映射关系,则返回 null。 
			 Map.Entry<K,V> higherEntry(K key) 
			          返回一个键-值映射关系,它与严格大于给定键的最小键关联;如果不存在这样的键,则返回 null。 
			 K higherKey(K key) 
			          返回严格大于给定键的最小键;如果不存在这样的键,则返回 null。 
			 Set<K> keySet() 
			          返回此映射包含的键的 Set 视图。 
			 Map.Entry<K,V> lastEntry() 
			          返回与此映射中的最大键关联的键-值映射关系;如果映射为空,则返回 null。 
			 K lastKey() 
			          返回映射中当前最后一个(最高)键。 
			 Map.Entry<K,V> lowerEntry(K key) 
			          返回一个键-值映射关系,它与严格小于给定键的最大键关联;如果不存在这样的键,则返回 null。 
			 K lowerKey(K key) 
			          返回严格小于给定键的最大键;如果不存在这样的键,则返回 null。 
			 int size() 
			          返回此映射中的键-值映射关系数。 
			 Collection<V> values() 
			          返回此映射包含的值的 Collection 视图。 
		 */
	}
}

三、LinkedHashMap(掌握)

3.1 定义

  • Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序。
  • 此实现与 HashMap 的不同之处在于,后者维护着一个运行于所有条目的双重链接列表。
  • 此链接列表定义了迭代顺序,该迭代顺序通常就是将键插入到映射中的顺序(插入顺序)。
  • 注意,如果在映射中重新插入 键,则插入顺序不受影响。

3.2 创建对象

LinkedHashMap() 
          构造一个带默认初始容量 (16) 和加载因子 (0.75) 的空插入顺序 LinkedHashMap 实例。 
LinkedHashMap(int initialCapacity) 
          构造一个带指定初始容量和默认加载因子 (0.75) 的空插入顺序 LinkedHashMap 实例。 
LinkedHashMap(int initialCapacity, float loadFactor) 
          构造一个带指定初始容量和加载因子的空插入顺序 LinkedHashMap 实例。 
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) 
          构造一个带指定初始容量、加载因子和排序模式的空 LinkedHashMap 实例。 
LinkedHashMap(Map<? extends K,? extends V> m) 
          构造一个映射关系与指定映射相同的插入顺序 LinkedHashMap 实例。 
package com.qf.linkedhashmap;

import java.util.LinkedHashMap;

public class Demo01 {
	public static void main(String[] args) {
		
		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
		map.put(10010, "中国联合通讯集团");
		map.put(95595, "中国光大银行");
		map.put(10000, "中国电信集团");
		map.put(10086, "中国移动通讯集团");
		System.out.println(map);
		
		map.put(10010, "中国联合通讯集团00");
		map.put(95595, "中国光大银行00");
		map.put(10000, "中国电信集团00");
		map.put(10086, "中国移动通讯集团00");
		System.out.println(map);
	}
}

四、Properties(掌握)

4.1 定义

  • Properties 类表示了一个持久的属性集。
  • Properties 可保存在流中或从流中加载。
  • 属性列表中每个键及其对应值都是一个字符串。

4.2 创建对象

Properties() 
          创建一个无默认值的空属性列表。 
Properties(Properties defaults) 
          创建一个带有指定默认值的空属性列表。 

4.3 案例

package com.qf.properties;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class Demo01 {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		// 创建Properties的对象
		Properties properties = new Properties();
		// 通过setProperty方法设置属性名和属性值
		properties.setProperty("url", "jdbd:mysql://localhost:8080");
		properties.setProperty("user", "root");
		properties.setProperty("password", "dushine");
		System.out.println(properties);
		
		// 通过getProperty获取执行属性名对应的属性值,如果不存在返回null
		System.out.println(properties.getProperty("url"));
		System.out.println(properties.getProperty("user"));
		System.out.println(properties.getProperty("password"));
		System.out.println(properties.getProperty("password00"));
		
		// 从本地文件中导入属性,这些属性会保存在properties对象中,可以使用getProperty方法或去指定的属性名对应的属性值
		properties.load(new FileInputStream("db.properties"));
		System.out.println(properties);
		System.out.println(properties.getProperty("url0"));
		System.out.println(properties.getProperty("user0"));
		System.out.println(properties.getProperty("password0"));
	}
}

五、异常(掌握)

5.1 定义

  • 程序在运行的过程中出现了无法处理的错误,由此引发的程序的终止称为异常
  • 程序运行过程中出现了错误,崩了

5.2 异常的分类

  • Throwable(类)
    • Error
      • 错误
      • 我们无法处理
      • 线程死了
      • 服务器宕机
      • 数据库崩了
    • Exception
      • 异常
      • 我们可以想办法处理
      • 空指针
      • 类型转换
      • 下标越界
      • … …

5.3 捕获异常

  • try…catch
  • try…catch…catch…catch.
package com.qf.exception;

import java.util.LinkedHashMap;

public class Demo02 {
	public static void main(String[] args) {
		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
		map.put(10010, "中国联合通讯集团");
		map.put(95595, "中国光大银行");
		map.put(10000, "中国电信集团");
		map.put(10086, "中国移动通讯集团");
		System.out.println(map);
		
		/**
		 * try{
		 * 	尝试运行可能报错的代码
		 * } catch(需要捕获的异常的类型 变量名){
		 * 	处理异常的代码
		 * 	输出异常的信息
		 * }
		 */
		
		try {
			System.out.println(map.get(100110).charAt(10));
			System.out.println(10 / 0);
		} catch (NullPointerException e) {
			System.err.println("有空指针异常");
			e.printStackTrace();
		} catch (ArithmeticException e) {
			System.err.println("算术运算异常");
		} catch (Exception e) {
			System.err.println("未知异常");
		}
		
		map.put(10010, "中国联合通讯集团00");
		map.put(95595, "中国光大银行00");
		map.put(10000, "中国电信集团00");
		map.put(10086, "中国移动通讯集团00");
		System.out.println(map);
	}
}

  • try…finally
package com.qf.exception;

import java.util.LinkedHashMap;

public class Demo03 {
	public static void main(String[] args) {
		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
		map.put(10010, "中国联合通讯集团");
		map.put(95595, "中国光大银行");
		map.put(10000, "中国电信集团");
		map.put(10086, "中国移动通讯集团");
		System.out.println(map);
		
		try {
			System.out.println(map.get(10).charAt(10));
		} finally {
			// 异常产生了,但是后面的代码需要依赖异常部分的代码才能执行,
			// 后面的代码没有必要运行,可能需要收尾/善后的工作,在finally代码块中执行
			// 关闭连接/释放资源/回滚到操作之前
			System.out.println("我是finally代码块");
		}
		
		map.put(10010, "中国联合通讯集团00");
		map.put(95595, "中国光大银行00");
		map.put(10000, "中国电信集团00");
		map.put(10086, "中国移动通讯集团00");
		System.out.println(map);
	}
}

  • try…catch…finally
  • try…catch…catch…catch…finally
package com.qf.exception;

import java.util.LinkedHashMap;

public class Demo04 {
	public static void main(String[] args) {
		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
		map.put(10010, "中国联合通讯集团");
		map.put(95595, "中国光大银行");
		map.put(10000, "中国电信集团");
		map.put(10086, "中国移动通讯集团");
		System.out.println(map);
		
		try {
			System.out.println(map.get(10).charAt(10));
		} catch (ArithmeticException e) {
			System.err.println("算术运算异常");
		} catch (NullPointerException e) {
			System.out.println("空指针异常,正在处理");
			System.out.println(10/0);
		} finally {
			// 处理异常的过程中崩了,在此处执行最后的操作
			System.out.println("他们都挂了,我来善后。");
		}
		
		map.put(10010, "中国联合通讯集团00");
		map.put(95595, "中国光大银行00");
		map.put(10000, "中国电信集团00");
		map.put(10086, "中国移动通讯集团00");
		System.out.println(map);
	}
}

  • try…try…catch…catch
package com.qf.exception;

import java.util.LinkedHashMap;

public class Demo04 {
	public static void main(String[] args) {
		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
		map.put(10010, "中国联合通讯集团");
		map.put(95595, "中国光大银行");
		map.put(10000, "中国电信集团");
		map.put(10086, "中国移动通讯集团");
		System.out.println(map);
		
		try {
			System.out.println(map.get(10).charAt(10));
		} catch (ArithmeticException e) {
			System.err.println("算术运算异常");
		} catch (NullPointerException e) {
			System.out.println("空指针异常,正在处理");
			// 异常处理的嵌套
			try {
				System.out.println(10/0);
			} catch (Exception e1) {
				System.out.println("处理异常的时候挂了,我来迁就他们");
			}
		} finally {
			// 处理异常的过程中崩了,在此处执行最后的操作
			System.out.println("我是善后的代码。");
		}
		
		map.put(10010, "中国联合通讯集团00");
		map.put(95595, "中国光大银行00");
		map.put(10000, "中国电信集团00");
		map.put(10086, "中国移动通讯集团00");
		System.out.println(map);
	}
}
package com.qf.exception;

import java.util.LinkedHashMap;

public class Demo04 {
	public static void main(String[] args) {
		try {
			try {
				System.out.println(10/0);
			} catch (Exception e) {
				e.printStackTrace();
			}
			LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
			map.put(10010, "中国联合通讯集团");
			map.put(95595, "中国光大银行");
			map.put(10000, "中国电信集团");
			map.put(10086, "中国移动通讯集团");
			System.out.println(map);
		
			System.out.println(map.get(10).charAt(10));
		
			map.put(10010, "中国联合通讯集团00");
			map.put(95595, "中国光大银行00");
			map.put(10000, "中国电信集团00");
			map.put(10086, "中国移动通讯集团00");
			System.out.println(map);
		} catch (ArithmeticException e) {
			System.err.println("算术运算异常");
		} catch (NullPointerException e) {
			System.out.println("空指针异常,正在处理");
			// 异常处理的嵌套
			try {
				System.out.println(10/0);
			} catch (Exception e1) {
				System.out.println("处理异常的时候挂了,我来迁就他们");
			}
		} finally {
			// 处理异常的过程中崩了,在此处执行最后的操作
			System.out.println("我是善后的代码。");
		}
	}
}
  • 异常处理的原则
    • 并不是try包裹的代码越多越好,要选择合适的代码用try运行
    • 多个异常可以使用多层catch来捕获,分别处理
      • 要注意:父类异常要写在后面的catch中
    • 异常处理的过程中可能再次产生异常,可以加上finally代码块做最后的工作
      • finally代码块无论如何都会被执行–除了遇到System.exit(0)

5.4 finally

  • 非常坚强的一个代码块
  • break、return都不能阻止finally代码块中内容的执行
  • 除非使用System.exit(0)
  • 可以用作程序最后释放资源、关闭连接、回滚数据的操作

5.5 异常的传递

5.6 抛出异常

  • 谁调用异常就传递给谁
  • 在整个异常传递的过程中,如果有一个地方对异常进行了捕获,异常就会被处理掉
  • 异常不想处理的时候可以使用throws抛出
    • 抛出异常的操作写在方法声明的后面
    • 可以一次写很多个,顺序从小到大写
package com.qf.exception;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Demo06 {
	public static void main(String[] args) {
		try {
			// 前面的都没有处理,如果在此处不处理就会抛给main方法,jvm不会处理,会终止程序运行
			show01();
		} catch (ArithmeticException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void show01() throws ArithmeticException, ParseException, Exception {
		System.out.println("show01开始执行");
		show02();
		System.out.println("show01执行结束");
	}

	private static void show02() throws ArithmeticException, ParseException, Exception {
		System.out.println("show02开始执行");
		show03();
		System.out.println("show02执行结束");
	}
	
	private static void show03() throws Exception, ArithmeticException, ParseException{
		System.out.println("show03开始执行");
		System.out.println("10/0" + (10/0));
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		// 代码可能产生异常,不想在此处处理,抛给方法的调用者解决
		sdf.parse("");
		
		System.out.println("show03执行结束");
	}
}

5.7 自定义异常

  • 官方提供的那些异常已经无法满足我制造异常的能力啦
  • 我们需要一些特定场景下的异常
package com.qf.exception;

public class Demo07 {
	public static void main(String[] args) {
		Stu stu = new Stu();
		stu.setAge(18);
		System.out.println(stu);
		
		stu.setAge(40);
		System.out.println(stu);
	}
}

class Stu{
	private String name;
	private int age;
	private double height;
	private double weight;
	
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		if (age > 30 || age < 18) {
			throw new AgeOutofBoundsException("年龄不符合我的要求");
		} else {
			this.age = age;
		}
	}
	
	public double getHeight() {
		return height;
	}
	
	public void setHeight(double height) {
		this.height = height;
	}
	
	public double getWeight() {
		return weight;
	}
	
	public void setWeight(double weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Stu [name=" + name + ", age=" + age + ", height=" + height + ", weight=" + weight + "]";
	}
	
}
/**
 * 	自定义异常
 * 		继承Exception或者RuntimeException
 * 		调用父类的构造方法,可以传入异常信息
 * 		使用的时候用throw new 自定义异常(参数);
 * @author Dushine2008
 * @version
 * @date 2020年6月11日
 */
class AgeOutofBoundsException extends RuntimeException{
	public AgeOutofBoundsException(String message) {
		super(message);
	}
}

六、正则(会用)

6.1 定义

  • 匹配字符串的规则
  • 正确的规则

6.2 正则关键类

  • String

  • Pattern

    • 编译正则字符串的类
    • 得到编译之后的正则对象
  • Matcher

    • 正则匹配后得到的结果
    • matches
    • find
    • group

6.3 案例

package com.qf.pattern;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo01 {
	public static void main(String[] args) {
		// 编译正则
		Pattern p = Pattern.compile("a*b");
		// 使用编译后的正则对象匹配字符串,结果存储在Matcher对象中
		Matcher m = p.matcher("aaaaab");
		// 获取匹配的结果
		boolean b = m.matches();
		
		System.out.println(b);
		
	}
}

package com.qf.pattern;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo02 {
	public static void main(String[] args) {
		/**
		 * 	用户名、密码
		 * 	手机号		18937012800
		 * 	邮箱
		 */
		// 编译正则
		Pattern p = Pattern.compile("1[3456789][\\d]{9}");
		// 使用编译后的正则对象匹配字符串,结果存储在Matcher对象中
		Matcher m = p.matcher("18937012800");
		
		boolean b = m.matches();
		System.out.println(b);
	}
}

package com.qf.pattern;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo03 {
	public static void main(String[] args) {
		/**
		 * 	用户名、密码
		 * 	手机号		18937012800
		 * 	邮箱			dushine@126.com
		 */
		// 编译正则表达式
		Pattern p = Pattern.compile("[a-zA-Z0-9]{6,30}@126.com");
		// 用编译后的正则表达式匹配邮箱,得到的结果存储在matcher中
		Matcher m = p.matcher("dushine@126.com");
		// 获取匹配的结果
		// boolean b = m.matches();
		// System.out.println(b);
		System.out.println(m.find());
		System.out.println(m.group());
	}
}

package com.qf.pattern;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo04 {
	public static void main(String[] args) {
		/**
		 * 	作业
		 * 	提取账号和密码
			 * 	优酷VIP账号:1454722052@qq.com 优酷会员密码:YouKuVip31079
				优酷VIP账号:9747565478@qq.com 优酷会员密码:YouKuVip206008
				优酷VIP账号:341585260@qq.com 优酷会员密码:YouKuVip842779
				优酷VIP账号:1406585019@qq.com 优酷会员密码:YouKuVip308766
				优酷VIP账号:11733153898@qq.com 优酷会员密码:YouKuVip970942
				优酷VIP账号:8730702752@qq.com 优酷会员密码:YouKuVip462334
				优酷VIP账号:11829427964@qq.com 优酷会员密码:YouKuVip415568
		 */
		String str = "优酷VIP账号:1454722052@qq.com 优酷会员密码:YouKuVip31079"
				+ "优酷VIP账号:9747565478@qq.com 优酷会员密码:YouKuVip206008"
				+ "优酷VIP账号:341585260@qq.com 优酷会员密码:YouKuVip842779"
				+ "优酷VIP账号:1406585019@qq.com 优酷会员密码:YouKuVip308766"
				+ "优酷VIP账号:11733153898@qq.com 优酷会员密码:YouKuVip970942"
				+ "优酷VIP账号:8730702752@qq.com 优酷会员密码:YouKuVip462334"
				+ "优酷VIP账号:11829427964@qq.com 优酷会员密码:YouKuVip415568";
		
		Pattern p = Pattern.compile("[0-9]{2,12}@qq.com");
		Matcher m = p.matcher(str);
		while (m.find()) {
			System.out.println(m.group());
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值