泛型,set,异常处理

目的:
1.学习泛型的定义和运用
2.学习set的有关方法
3.了解异常处理,并熟悉运用
知识点部分:

  1. 泛型-void
  • 泛型类 泛型方法 泛型数组
  • (对象类型,基本数据类型需要包装)
    2.set
    1.集合里面对象不能重复 如果重复 加不进去
    内部使用HashMap 来实现 键值对 键key不能重复
    2.集合是无序的 添加顺序 与存储的顺序无关
    内部有默认排序
    技术实施:
    泛型定义及运用:
GenericTest<String> g1 = new GenericTest<>();

g1.test("jack","jacker");
class GenericTest<T>{
    int age;
    T a1;
    T a2;

    public void test (T a1,T a2){
        this.a1= a1;
        this.a2 = a2;
        System.out.println(a1.equals(a2));
    }
}

HashSet的运用:

HashSet<String> names = new HashSet<>();
        names.add("jack");
        names.add("merry");
        names.add("abc");
        names.removeIf(ele -> {return ele.compareTo("c")>0;});

HashMap运用:

HashMap 集合 存储数据的特点:键key-值value
        //key不能重复 可以是任意对象类型 通常情况下使用字符串String
        HashMap<String,Integer>score = new HashMap<>();
        //添加对象: 键值对
        score.put("Chinese",91);
        score.put("Math",93);
        score.put("English",95);
        //获取键值对的个数
        score.size();
        //获取所有的key
        System.out.println(score.keySet());
        //获取所有的value
        System.out.println(score.values());
        //获取Entry:key-value
        System.out.println(score.entrySet());
        //获取一个键key对应的值

        System.out.println(score.get("English"));
class Person {
    String name;
    int age;
    public Person(String name, int age){
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return super.toString();
    }

异常处理:
如果异常出现后面的代码将不会出现

  • try代码块不是越多越好 不要抓太多代码
  • 使用throws抛出异常 给外部处理
    特殊情况出现 自己可以选择抛出异常
 public static void main(String[] args){

        int a=0;
        int b=20;
        FileReader fr= null;
        try {
            int c=b/a;

        fr = new FileReader("");
        }catch ( ArithmeticException e){
            System.out.println(e.getMessage());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try{
            fr.close();}catch (IOException i){}
        }
//圆括号只能添加能够关闭的对象
        //实现了Closeable接口的对象
        //如果出先异常 系统自己就会关闭这个资源
        try(FileReader fr1= new FileReader("ddd")){
            //使用对象
        }catch(IOException e) {
            e.printStackTrace();
        }

        try{TException.test();
        }
        catch(FileNotFoundException e){
            e.printStackTrace();
        }
    }
class TException {
    public static void test()throws FileNotFoundException,NullPointerException{
        FileReader fr = new FileReader("DDD");
    }
    public static void test2()throws IllegalAccessException{

        if(2>1){
            throw new IllegalAccessException();
        }


    }
}
class PJMException extends Exception{
    //1.提供一个无参构造方法
    public PJMException(){

    }
    //
    public  PJMException(String desc){

    }

}

小结:
今天的东西与昨天的讲的有些类似,所以讲的也易于理解,讲的东西也少了。但是不能松懈,得弄清弄透。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容