Java-(泛型,集合-Set,HashMap,异常处理)


心得体会

  • 有时候上课认真听讲效率胜过课后自己花费大量时间再去学习,上课边听边有意识的整理笔记胜过课后去整理自己杂乱的笔记要来的轻松。如果自己在课上写代码的时候有意识的将代码模块化,课后再去整理就会轻松很多。一个好习惯的养成是长久的坚持。

今日知识点

  • 1.泛型
  • 2.集合-Set(hashSet)
  • 3.TreeSet进行排序的两种办法
  • 4.HashMap的方法
  • 5.键值对的两种遍历方式
  • 6.异常处理

具体操作

1.泛型

  • 1.什么是泛型

泛型就是指参数化类型,例如:List就是参数化类型,因此就是泛型,而String就是该List泛型的类型参数;

  • 2.为什么要使用泛型

通过泛型可以定义类型安全的数据结构(类型安全),而无须使用实际的数据类型(可扩展)。这能够显著提高性能并得到更高质量的代码(高性能),因为您可以重用数据处理算法,而无须复制类型特定的代码(可重用)

  • 3.泛型基础小demo

demo里面定义了一个泛型类GenericTest,其中里面的T表示参数类型,在main函数里面使用了该泛型类GenericTest g1=new GenericTest<>(),此时数据类型被定义为String

public class Myclass {
    public static void main(String[] args){
        GenericTest g1=new GenericTest<>();//尖括号里面一定是 对象类型
        g1.test("jack","jacker");
}
}
//定义了一个泛型类,其中‘T’代表不确定的对象类型
class GenericTest{
    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));
    }
}
image.png

ps:

1.类型变量使用大写形式,比较短。在java库中,变量E表示集合的元素,KV分别表示表的关键字与值的类型。T表示“任意类型”。
2.,泛型里面,的类型变量一定是对象类型 (例如:类型为整形时,使用时T应该为Integer,而不是int

2.集合-Set(hashSet、TreeSet)

Collection--List--ArrayList
                  --Set---HashSet
                       ---LinkedHashSet
                       ---TreeSet
  • 1. Set接口的特点

1.它是个不包含重复元素的集合。
2.Set集合取出元素的方式可以采用:迭代器、增强for。
3.Set集合有多个子类,这里我们介绍其中的HashSet、TreeSet这两个集合。

  • 2.HashSet
  • 2..HashSet方法的使用
        HashSet names=new HashSet<>();
        names.add("jack");
        names.add("merry");
        System.out.println(names);
image.png
    1. 集合里面对象不能重复 , 如果重复 ,就加不进去
HashSet names=new HashSet<>();
        names.add("jack");
        names.add("jack");
        System.out.println(names);
image.png
  • 2.集合是无序的, 添加的顺序和存储的顺序无关, 里面使用了默认排序
      HashSet names=new HashSet<>();
      names.add("jack");
      names.add("Merry");
      names.add("abc");
      System.out.println(names);
image.png
  • 3.使用compareTo()方法进行比较筛选
 HashSet names=new HashSet<>();
        names.add("jack");
        names.add("merry");
        names.add("abc");
        names.removeIf(ele->{
          return ele.compareTo("c")>0;
        });
        System.out.println(names);
image.png
  • 通过CompareTo()方法将字符串组里面的“jack”“merry”移除
  • 这里用了Lambda表达式,由于"j"、"m">"c",所以"jack","merry"被移除, 字符串的比较,是一个一个按顺序从头到尾轮流比的,如果字符串前面的字符已经比较出结果了,那么后面的也不需要比了

3.TreeSet进行排序的两种办法

  • 1.TreeSet的性质
  • TreeSet是可以排序的集合,有序的集合

1.TreeSet的第一种排序方法----自然排序

1.这种方法需要一个新的类实现Comparator接口

2.重写其中的Compare 方法

  TreeSet score=new TreeSet<>(new Comparator() {
            @Override
            public int compare(Person person, Person t1) {
              return person.compareTo(t1);
                }
        });
}
}
class Person implements Comparable {
    String name;
    int age;

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


    //
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

   @Override
    public int compareTo(Object o) {
        //1.判断o对象是不是person的一个对象
        if(o instanceof Person){
            Person o1=(Person)o;
          //自己规定比较的策略
            if(this.age!=o1.age){
                return this.age-o1.age;
            }else{
                //年龄相同的情况下 再比姓名的字母
                return this.name .compareTo(o1.name);
            }
        }else{
            return -1;
        }
    }
}

2.TreeSet的第二种排序方法----自然排序
1, 需要被排序的类实现Comparable接口(参与比较的对象必须实现Comparable接口的compareTo方法)

2, 重写其中的 comparato

 TreeSet score=new TreeSet<>((Person p1,Person p2)->p1.compareTo(p2)) ;
        Person p1=new Person("jack",20);
        Person p2=new Person("jack",30);
        Person p3=new Person("rose",20);

        score.add(p1);
        score.add(p2);
        score.add(p3);
        System.out.println(score);
}
}
class Person implements Comparable {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
  //参与⽐比较的对象必须实现Comparable接⼝口的compareTo⽅方法
   @Override
    public int compareTo(Object o) {
        //1.判断o对象是不是person的一个对象
        if(o instanceof Person){
            Person o1=(Person)o;
          //自己规定比较的策略
            if(this.age!=o1.age){
                return this.age-o1.age;
            }else{
                //年龄相同的情况下 再比姓名的字母
                return this.name .compareTo(o1.name);
            }
        }else{
            return -1;
        }
    }
}

4.HashMap

image.png
  • HashMap是一种集合
    存储数据的特点:key->value
    key(键):不能重复 可以是任意的对象类型 通常使用字符串String
  • HashMap的方法
方法 作用
put() 可以添加对象,也可以更改某个键对应的值
size() 获取键的个数
keySet() 获取所有的key(键)
values() 获取所有的值
entrySet() 获取每一个键值对
get() 获取每一个键对应的值
 HashMap score=new HashMap<>();//键的类型是String ,值的类型是Integer

        //添加对象 键值对
        score.put("Chinese",89);
        score.put("Math",94);
        score.put("English",92);
        System.out.println(score);
        System.out.println();

        //更改某个键对应的值
        score.put("Chinese",91);//如果已经有同样的键,就会默认更改该键对应的值
        System.out.println(score);
        System.out.println();

        //获取键的个数
        score.size();
        System.out.println();

        //获取所有的key
        System.out.println(score.keySet());
        System.out.println();

        //获取所有的值
        System.out.println(score.values());
        System.out.println();

        //获取Entry:key-value
        System.out.println(score.entrySet());//获取每一个键值对
        System.out.println();


        //获取一个键key对应的值
        System.out.println(score.get("English"));

image.png

5.键值对的两种遍历方式

1.键值对的第一种遍历方式--- 通过遍历key来得到每一个key对应的值

 HashMap score=new HashMap<>();//键的类型是String ,值的类型是Integer
        //添加对象 键值对
        score.put("Chinese",89);
        score.put("Math",94);
        score.put("English",92);

        for(String key:score.keySet()){
            //通过key得到值
            int s=score.get(key);
            System.out.println("key:"+key+" value :"+s);
        }

2.键值对的第二种遍历方式--- 通过entrySet 得到Entry对象的集合


 HashMap score=new HashMap<>();//键的类型是String ,值的类型是Integer
        //添加对象 键值对
        score.put("Chinese",89);
        score.put("Math",94);
        score.put("English",92);

 Set> entrys = score.entrySet();//先接受每一个键值对的对象
        for (Map.Entry entry : entrys) {
            //得到Entry对应的key
            String key = (String) entry.getKey();
            //获取Entry对应的值
            Integer value = (Integer) entry.getValue();
            System.out.println("key:" + key + " value :" + value);

        }
    }
}

运行结果


image.png

6.异常处理

1.异常处理:处理运行过程中出现的不可控的错误,使程序更健壮

1.在我们编写异常处理代码的时候,主要就是使用前面介绍到的try-catch-finally这三种代码块。

try{
      执行可能出现异常的代码
     一旦出现异常 系统自动为我们创建一个异常对象 并抛出
  }catch(NullPointerException e){
      如果需要 自己处理异常就catch
  }catch(IOException e){
      如果有多个异常 可以使用多个catch来捕获
  }catch(Exception e){
 
  }finally{
     处理资源回收( 网络链接 数据库连接 IO流)
      1.不管有没有异常finally都会被执行
  }
  public static void main(String[] args) {
        int a = 0;
        int b = 20;
        FileReader fr = null;
        try {
            int c = b / a;

            fr = new FileReader("");
//          System.out.println("hello");//不会打印
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException i) {

            }
        }
    }
}
  • 如果有多个异常 catch的顺序是从小到大
try{
     
  }catch(NullPointerException e){
     
  }catch(IOException e){
      
  }catch(Exception e){
 
  }
  • 如果异常出现 后面的代码将不会执行(try代码块不是越多越好 不要抓太多代码)
  • 看下面一段代码:
public class Exception1 {
    public static void main(String[] args) {
        int a = 0;
        int b = 20;
        try {
            int c = b / a;
  } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}
image.png
  • 如果在try里面在加上一行代码:
public class Exception1 {
    public static void main(String[] args) {
        int a = 0;
        int b = 20;
        try {
            int c = b / a;
           System.out.println("hello");//不会打印
  } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}
image.png

输出结果是一样的


2.使用throws抛出异常 给外部处理

 public static void test() throws FileNotFoundException, NullPointerException {//如果有多个异常,用逗号隔开
        FileReader fr = new FileReader("");
    }

3.使用throw抛出⼀一个自己创建的异常对象

当特殊情况出现了 自己可以选择抛出异常
throw new IllegalAccessException();

 public static void test2() throws IllegalAccessException {
        if (2 > 1) {
            throw new IllegalAccessException();
}

4.自定义异常类: 能够自己定义输出内容 更快地找到出现问题的位置

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

    }
    //2.提供一个有参构造方法 参数是一个字符串
    public PXDException(String desc){
        super(desc);
    }
}
 public static void test3() throws PXDException{

        StackTraceElement[] stackTrace=Thread.currentThread().getStackTrace();
        StackTraceElement e=stackTrace[2];
        String detail=" "+e.getFileName()+"->"+e.getMethodName()+"->"+e.getLineNumber();
        throw new PXDException("自己的异常类:无所作为"+detail);
    }
}
  • 使用
     }
        try {
            TException.test3();
        }catch(PXDException e){
            System.out.println(e.getMessage());
        }

image.png

你可能感兴趣的:(Java-(泛型,集合-Set,HashMap,异常处理))