zoukankan      html  css  js  c++  java
  • Java集合框架的学习

    本节内容总结来自传智播客毕向东老师的公开课,感谢毕向东老师 !如有错误之处,欢迎大家指教 !

    Collection集合常用方法:

      增加、删除、大小、包含、为空、清空、迭代、并交差;

      boolean add(E o);  boolean remove(Object o);  int size();  boolean contains(Object o);  boolean isEmpty();  void clear();  Iterator<E> iterator();

      boolean addAll(Collection c);  boolean retainAll(Collection c);  boolean removeAll(Collection c);

    Set集合常用的方法:

      Collection集合拥有的方法一样;

    List集合常用的方法:

      List集合的方法中,带索引参数(角标)的都是新增的方法;带角标的操作都是数组原理;

      除了继承Collection集合的方法,还有以下自己独有的方法,都与索引(下标)有关:

      增加、删除、修改(只能是修改,不能是插入)、查找(获取)元素、查找元素所在位置(两种);

      void add(int index, E e);  E remove(int index);  E set(int index, E e);  E get(int index);  int indexOf(Object o);  int lastIndexOf(Object o);

    Map集合常用的方法:

      增加、删除、修改、查找(获取)、大小、包含、为空、清空、迭代

      V put(K k, V v);  V remove(Object k);  put()方法也起到修改功能  V get(Object k);  int size();  boolean containsKey(Object k);

      boolean containsValue(Object v);  boolean isEmpty();  void clear();

    为什么会有集合;

    为什么会有这么多不同的集合框架;

    集合与数组的区别;

    集合类的关系图;

    集合中存放的是对象实体还是对象的引用(地址),并想一下内存图;

    集合中取出元素并操作的常用方法;

    集合中获取所有元素的常用方法;

    Collection接口的常见两个子接口及比较;

    List接口下的常用类及比较;

    List集合独有的迭代器;

    Vector特有的迭代器(枚举);

    LinkedList中一些方法的版本迭代;

    List集合中如何实现去除重复元素;

    Set接口下的常用类及比较;

    Set集合中,如何实现去除重复元素;

    Set集合中,如何实现对元素进行排序;(应该不是只针对TreeSet集合);

    泛型;

    Map集合下的常用类;

    Map集合取出元素的方法;

    集合框架中的工具类;

    增强型for循环;

    为什么会有集合:

      数据多了,用对象存;对象多了,用集合(和数组)存;

    为什么会有这么多不同的集合框架(容器):

      因为每个容器对数据的存储方式都有不同;存储方式就是指数据结构;

    集合与数组的区别:

     数组的长度是固定的,集合的长度是可变的;

     数组只能存储同一类型数据,集合能存储不同类型数据;

     数据可以存基本类型数据,集合只能存对象;

    集合框架的关系图:

     集合框架的关系图

    集合中存放的是对象实体还是对象的引用(地址)

      集合中存放的都是对象的引用(地址);

    集合中取出元素并操作的常用方法:

      使用迭代器:就是集合中取出元素的一种方式;

      有的接口(实现类)有专门的取出元素的方法:

      List集合中:get(index)  subList(from,to)  Iterator

    集合中获取所有元素的常用方法:

      for循环

      加强型for循环

      迭代器

    Collection接口的常见两个子接口及比较:

     List接口:

      元素是有序的,元素可以重复,因为有索引;

     Set接口:

      元素是无序的(存入和取出的顺序不一定一致),元素不可以重复;

    List接口下的常用类及比较:

    ArrayList:底层的数据结构使用的是数组结构;  特点:查询元素速度很快,但增删稍慢;  线程不同步

    LinkedList:底层的数据结构使用的是链表结构;  特点:增删速度很快,但查询稍慢;

    Vector:底层的数据结构使用的是数组结构;  特点:查询,增删速度都很慢,被ArrayList替换了;  线程同步

    java集合框架还专门提供加锁的功能,把你不安全的给我,我给你安全的,解决线程不同步问题;

    List集合独有的迭代器:

      ListIterator(接口),继承自Iterator接口;

      使用迭代器过程中,有两种操作元素的方式:使用集合对象的方法操作元素;使用迭代器的方法操作元素;

      在迭代时,不可以用集合对象的方法操作集合中的元素,因为会发生并发修改异常;要用迭代器自己的方法操作数据;

      Iterator接口只有删除元素的操作,而ListIterator接口有增加、删除、修改等操作;(实例中有疑问)

    Vector特有的迭代器(枚举):

      已经被Iterator替代,因为它的功能和Iterator一样,但它的名称和它的方法名过长,没有Iterator好使;

    LinkedList中一些方法的版本迭代:

    JDK1.6之前:

      addFirst()addLast():添加元素

      getFirst()getLast():获取元素,但不删除元素;如果集合中没有元素,会抛出NoSuchElementException

      removsFirst()removeLast():获取元素,但同时元素也被删除;如果集合中没有元素,会抛出NoSuchElementException

    JDK1.6之后:

      offerFirst()offerLast():添加元素

      peekFirst()peekLast():获取元素,但不删除元素;如果集合中没有元素,返回null

      pollFirst()pollLast():获取元素,但同时元素也被删除;如果集合中没有元素,返回null

    获取所有元素并删除的实现:

      使用迭代器;

      使用 pollFirst()pollLast()方法:

      while( ! link.isEmpty() )

      {

          syso(link.pollFirst());

      }

    List集合中判断元素是否相同的问题:

      集合中有自己的判断元素的方法,但不符合需求的话,就要程序员自己定义判断规则;

      集合自身只能判断对象是否相同,用equals()方法来判断:obj1.equals(obj2);而继承自Object类的equals()方法是判断对象是否相同时判断的是对象的地址是否相同;但如果具体判断对象的属性值是否相同时,equals()方法就相当于判断对象的内容而不是地址是否相同的(其实此时用的是String类中的判断字符串内容是否相同的方法,已经重写的继承自Object类的equals()方法);

      List集合中的contains()remove()两个方法底层都是用equals()方法来实现的;

      程序员自己通过修改继承自Object类的equals()方法来自定义判断规则,使自定义类具体可比较性;

    Set集合的两个子类:

    HashSet:底层的数据结构使用的是Hash表;

    TreeSet:底层数据结构是二叉树;可以对Set集合中的元素进行排序,以自然顺序进行排序;

    HashSet是如何保证元素唯一性的:

    是通过元素的两个方法:hashCode()equals()

    如果元素的hashCode值相同,才会调用equals()判断是否为true

    如果元素的hashCode值不同,不会调用equals()判断是否为true

    注意:对于判断元素是否存在,以及元素删除等操作,依赖的方法是元素的hashCode()equals()方法,先使用hashCode()ArrayList只依赖equals()方法;

    所以开发中,往集合中添加元素时,一般都会覆写hashCode()equals()方法;

    TreeSet集合对元素进行排序:

      TreeSet保证元素唯一性:依靠compareTo()方法返回值;

      TreeSet集合本身会对元素进行按自然顺序进行排序,但在实际开发中肯定不满足需求,需要程序员自定义排序规则;

      元素被放入TreeSet集合之前,必须是可以被排序的(告诉TreeSet集合如何排序),不然程序运行时会报错;或者元素不具备比较性,然TreeSet集合本身实现需要的比较规则也可以;

      TreeSet集合的两种排序方式:

        第一种:当元素不具备比较性,强制使元素具备比较性,继承Comparable接口;

        第二种:当元素不具备比较性,或者元素具备的比较性不是所需要的,实现让集合本身具备比较性;实现:在集合初始化时,就具有比较性,所以是对构造函数进行改造;

        注意:

          当两种排序都存在时,以比较器(Comparator)为准;

          排序时,当主要条件相等时,必须要再判断次要条件,直到能排除一个顺序出来;

    泛型:

      JDK1.5之后出现的泛型,解决安全问题,是一种安全机制;

      好处:

        将运行时期出现的类型转换异常转移到了编译时期,方便于程序员解决问题,让运行时期出现问题较少;

        避免了强制转换的麻烦;

      什么时候使用泛型:

        通常在集合框架中很常见;

        只要见到<>就要定义泛型;

      其实<>就是用来接收类型的,当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可;

      什么时候使用泛型类:

        当类中要操作的引用数据类型不确定的时候使用泛型类;

      早期通过定义Object来完成扩展,现在通过定义泛型来完成扩展;

      方法删规定以泛型比类上定义泛型扩展性更好;

      当类上个方法上都定义泛型时,并不冲突,以方法上定义的泛型为准;

      泛型类上定义的泛型,在整个类中有效,如果被方法使用,那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了;为了让不同方法可以操作不同类型,而且类型还不确定,那么可以将泛型定义在方法上;注意:静态方法不可以访问类上定义的泛型,所以如果静态方法操作的引用数据类型不确定的话,可以将泛型定义在静态方法上;

      泛型的限定:

        ? extends E:可以接收E类型或者E的子类型,上限;

        ? super E:可以接收E类型或者E的父类,下限;

    Map集合下的常用类:

    HashTable:底层的数据结构使用的是哈希表; 不可以存入nullnull值; 该集合是线程同步的;  效率低;

    HashMap:底层的数据结构使用的是哈希表; 可以存入nullnull值; 该集合不是线程同步的;  效率高;

    TreeMap:底层的数据接口使用的是二叉树; 线程不同步; 可以用于给Map集合中的键进行排序;

    将数组变成集合,不可以使用集合的增删方法,因为数组的长度是固定的;

    如果数组中的元素都是对象,那么转成集合时,数组中的元素就直接转成集合中的元素;

    如果数组中的元素都是基本类型,那么会将该数组作为集合中的元素存在;

    集合转成数组时,指定类型的数组要定义成多长:当指定类型数组的长度小于集合的size时,那么该方法的内部会创建一个新的数组,长度为集合的size;当指定类型数组的长度大于集合的size时,该方法不会再创建一个新的数组,而是使用传递过来的数组;所以创建一个刚刚好的数组最优;

    为什么要将集合转成数组:

      限定对元素的操作;集合可以增删元素,转成数组之后,就能进行元素增删操作了;

    foreach

    只能获取集合中的元素,但不能对集合进行操作;

    迭代器:

    除了遍历集合元素,还可以进行remove集合中元素的操作;

    如果使用ListIterator,还可以在遍历元素时候进行增删改查的动作;

    forforeach的区别:

    foreach必须有被遍历的目标;

    方法的可变参数一定要定义在参数列表的最后面;

    静态导入:

    当类重名时,需要指定具体的包名;

    当方法重名时,需要制定具体的所属对象或类;

    一些实例:

     1 /**
     2  * 迭代器的使用
     3  */
     4 package collection;
     5 
     6 import java.util.ArrayList;
     7 import java.util.Iterator;
     8 
     9 public class IteratorDemo
    10 {
    11     public static void main(String[] args)
    12     {
    13         iterator();
    14     }
    15     
    16     public static void iterator()
    17     {
    18         // 现在集合中添加元素
    19         ArrayList al = new ArrayList();
    20         al.add("java1");
    21         al.add("java2");
    22         al.add("java3");
    23         
    24         // 使用迭代器,可以对每一个元素进行操作
    25         // 通过iterator()方法获得Iterator接口的子对象
    26         Iterator it = al.iterator();  
    27         // 判断后面是否还有元素
    28         while(it.hasNext())
    29         {
    30             // 打印出后面这个元素
    31             System.out.println(it.next());
    32         }
    33 
    34          // 另外一种书写方式
    35         // 使用这种方式,迭代器对象使用完之后就被销毁了
    36         for(Iterator it2 = al.iterator(); it2.hasNext(); )
    37         {
    38             System.out.println(it2.next());
    39 }
    40     }
    41 }
     1 /**
     2  * 功能:List集合特有的迭代器
     3  */
     4 package collection;
     5 
     6 import java.util.ArrayList;
     7 import java.util.Iterator;
     8 import java.util.ListIterator;
     9 
    10 public class IteratorDemo2
    11 {
    12     public static void main(String[] args)
    13     {
    14         // iterator();
    15         listIterator();
    16     }
    17     
    18     public static void iterator()
    19     {
    20         ArrayList al = new ArrayList();
    21         al.add("java1");
    22         al.add("java2");
    23         al.add("java3");
    24         System.out.println(al);
    25         
    26         Iterator it = al.iterator();  
    27         while(it.hasNext())
    28         {
    29             Object obj = it.next();
    30             if(obj.equals("java2"))
    31             {
    32                 // 以下写法是错误的,会产生并发异常
    33                 // 对元素操作,要么全用集合的方法,要么全用迭代器的方法
    34                 // al.add("java4");
    35                 
    36                 // 将java2的引用从集合中删掉
    37                 // 迭代器本身只有这个删除元素方法,比较局限
    38                 it.remove();
    39             }
    40             
    41             // 还是能打印出java2,因为obj还在引用它
    42             System.out.println(obj);
    43         }
    44         
    45         // 打印不出来java2了,因为al对它的引用已经被删掉了
    46         System.out.println(al);
    47     }
    48     
    49     public static void listIterator()
    50     {
    51         ArrayList al = new ArrayList();
    52         al.add("java1");
    53         al.add("java2");
    54         al.add("java3");
    55         System.out.println(al);
    56         
    57         ListIterator lit = al.listIterator();
    58         while(lit.hasNext())
    59         {
    60             Object obj = lit.next();
    61             if(obj.equals("java2"))
    62             {
    63                 // 在java2后面添加一个java4
    64                 lit.add("java4");
    65             }
    66             System.out.println(obj);
    67         }
    68         
    69         System.out.println(al);
    70     }
    71 }
     1 /**
     2  * 功能:Vector特有的迭代器,枚举 
     3  */
     4 package collection;
     5 
     6 import java.util.Enumeration;
     7 import java.util.Vector;
     8 
     9 public class VectorDemo
    10 {
    11     public static void main(String[] args)
    12     {
    13         Vector vt = new Vector();
    14         vt.add("java1");
    15         vt.add("java2");
    16         vt.add("java3");
    17         
    18         Enumeration<String> ea = vt.elements();
    19         while(ea.hasMoreElements())
    20         {
    21             System.out.println(ea.nextElement());
    22         }
    23     }
    24 }
     1 /**
     2  * 功能:集合中去除重复元素
     3  */
     4 package collection;
     5 
     6 import java.util.ArrayList;
     7 import java.util.Iterator;
     8 
     9 public class RevDuplElement
    10 {
    11     public static void main(String[] args)
    12     {
    13         ArrayList list = new ArrayList();
    14         list.add("one");
    15         list.add("one");
    16         list.add("two");
    17         list.add("two");
    18         list.add("three");
    19         list.add("three");
    20         
    21         System.out.println(test(list));
    22     }
    23     
    24     public static ArrayList test(ArrayList list)
    25     {
    26         ArrayList newList = new ArrayList();
    27         Iterator it = list.iterator();
    28         while(it.hasNext())
    29         {
    30             Object obj = it.next();
    31             if(!newList.contains(obj))
    32             {
    33                 newList.add(obj);
    34             }
    35         }
    36         return newList;
    37     }
    38 }
     1 /**
     2  * 功能:向下转型
     3  */
     4 package collection;
     5 
     6 import java.util.ArrayList;
     7 import java.util.Iterator;
     8 
     9 public class Convert
    10 {
    11     public static void main(String[] args)
    12     {
    13         ArrayList<Person3> list = new ArrayList<Person3>();
    14         list.add(new Person3("zhangsan",25));
    15         // add()方法里面的参数对象是Object,所以上面一句涉及到向上转型,具体如下
    16         // Object obj = new Person3("zhangsan",25);
    17          // list.add(obj);
    18         list.add(new Person3("lisi",26));
    19         list.add(new Person3("wangwu",27));
    20         
    21         // 没有使用泛型
    22         Iterator it = list.iterator();
    23         while(it.hasNext())
    24         {
    25             // 下面这样写(在没有使用泛型的情况下)是错误的,因为it.next()返回的对象是Object类型,不是Person3类型
    26             // 所以不会有getName()方法,需要向下转型
    27             // System.out.println("name" + it.next().getName());
    28             
    29             // 正确操作
    30             Person3 person = (Person3) it.next();
    31             System.out.println("name:" + person.getName() + ",age:" + person.getAge());
    32         }
    33         
    34         // 使用泛型
    35         Iterator<Person3> it2 = list.iterator();
    36         while(it2.hasNext())
    37         {
    38             System.out.println("name:" + it2.next().getName());
    39             // 不能这样写,因为每用一次next()都是找后面一个元素,而不是使用当前元素
    40             // System.out.println("name:" + it2.next().getName() + ",age:" + it2.next().getAge());
    41         }
    42     }
    43 }
    44 
    45 class Person3
    46 {
    47     private String name;
    48     private int age;
    49     
    50     public Person3(String name, int age)
    51     {
    52         this.name = name;
    53         this.age = age;
    54     }
    55     
    56     public String getName()
    57     {
    58         return name;
    59     }
    60     public void setName(String name)
    61     {
    62         this.name = name;
    63     }
    64     public int getAge()
    65     {
    66         return age;
    67     }
    68     public void setAge(int age)
    69     {
    70         this.age = age;
    71     }
    72     
    73     @Override
    74     public String toString()
    75     {
    76         return "Person [name=" + name + ", age=" + age + "]";
    77     }
    78     
    79 }
      1 /**
      2  * 功能:List集合中,重写equals方法,自定义判断规则
      3  * 通过比较,去除集合中相同的元素
      4  */
      5 package collection;
      6 
      7 import java.util.ArrayList;
      8 import java.util.Iterator;
      9 
     10 public class EqualsTest
     11 {
     12     public static void main(String[] args)
     13     {
     14         ArrayList list = new ArrayList();
     15         list.add(new Student4("lisi01", 25));
     16         list.add(new Student4("lisi01", 25));
     17         list.add(new Student4("lisi02", 22));
     18         list.add(new Student4("lisi03", 23));
     19         list.add(new Student4("lisi02", 22));
     20         list.add(new Student4("lisi03", 23));
     21         
     22         list = com(list);
     23         
     24         Iterator it = list.iterator();
     25         while(it.hasNext())
     26         {
     27             Student4 student = (Student4) it.next();
     28             System.out.println(student.getName() + "," + student.getAge());
     29         }
     30     }
     31     
     32     public static ArrayList com(ArrayList list)
     33     {
     34         ArrayList newList = new ArrayList();
     35         Iterator it = list.iterator();
     36         while(it.hasNext())
     37         {
     38             Object obj = it.next();
     39             // contains()底层是用equals()方法来实现的
     40             // 让Studnet4的两个对象使用equals()来比较
     41             // 所以要修改Studnet4的equals()方法
     42             if(!newList.contains(obj))
     43             {
     44                 newList.add(obj);
     45             }
     46         }
     47         
     48         return newList;
     49     }
     50 }
     51 
     52 class Student4
     53 {
     54     private String name;
     55     private int age;
     56     
     57     public Student4(String name, int age)
     58     {
     59         this.name = name;
     60         this.age = age;
     61     }
     62     
     63     // 覆盖继承自Object的equals()
     64     //  形参类型必须是Object,否则不是继承自Object类的方法
     65     public boolean equals(Object obj)
     66     {
     67         // 注意:obj必须放在前面
     68         if(! (obj instanceof Student4))
     69         {
     70             return false;
     71         }
     72         
     73         Student4 student = (Student4) obj;
     74         if(this.name.equals(student.getName()) && this.age==student.getAge())
     75         {
     76             return true;
     77         }
     78         else
     79         {
     80             return false;
     81         }
     82         
     83     }
     84 
     85     public String getName()
     86     {
     87         return name;
     88     }
     89 
     90     public void setName(String name)
     91     {
     92         this.name = name;
     93     }
     94 
     95     public int getAge()
     96     {
     97         return age;
     98     }
     99 
    100     public void setAge(int age)
    101     {
    102         this.age = age;
    103     }
    104     
    105 }
      1 /**
      2  * 功能:重写hashCode()方法
      3  * Set集合中比较元素首先用hashCode()判断地址是否相等
      4  * 再用equals()判断元素内容是否相等
      5  */
      6 package collection;
      7 
      8 import java.util.HashSet;
      9 import java.util.Iterator;
     10 
     11 public class HashCodeTest
     12 {
     13     public static void main(String[] args)
     14     {
     15         HashSet set = new HashSet();
     16         set.add(new Student5("lisi01",21));
     17         set.add(new Student5("lisi02",22));
     18         set.add(new Student5("lisi03",23));
     19         set.add(new Student5("lisi02",22));
     20         
     21         set = com(set);
     22         
     23         Iterator it = set.iterator();
     24         while(it.hasNext())
     25         {
     26             Student5 student = (Student5) it.next();
     27             System.out.println(student.getName() + "," + student.getAge());
     28         }
     29     }
     30     
     31     public static HashSet com(HashSet set)
     32     {
     33         HashSet newSet = new HashSet();
     34         Iterator it = set.iterator();
     35         while(it.hasNext())
     36         {
     37             Object obj = it.next();
     38             if(!(newSet.contains(obj)))
     39             {
     40                 newSet.add(obj);
     41             }
     42         }
     43         return newSet;
     44     }
     45 }
     46 
     47 class Student5
     48 {
     49     private String name;
     50     private int age;
     51     
     52     public Student5(String name, int age)
     53     {
     54         this.name = name;
     55         this.age = age;
     56     }
     57     
     58     // 重写hashCode()方法
     59     public int hashCode()
     60     {
     61         return name.hashCode() + age;
     62     }
     63     
     64     // 重写equals()方法
     65     public boolean equals(Object obj)
     66     {
     67         if(! (obj instanceof Student5))
     68         {
     69             return false;
     70         }
     71         
     72         Student5 student = (Student5) obj;
     73         if(this.name.equals(student.getName()) && this.age == student.getAge())
     74         {
     75             return true;
     76         }
     77         else
     78         {
     79             return false;
     80         }
     81     }
     82     
     83     public String getName()
     84     {
     85         return name;
     86     }
     87     public void setName(String name)
     88     {
     89         this.name = name;
     90     }
     91     public int getAge()
     92     {
     93         return age;
     94     }
     95     public void setAge(int age)
     96     {
     97         this.age = age;
     98     }
     99     
    100 }
     1 /**
     2  * 功能:Comparable接口的使用
     3  */
     4 package collection;
     5 
     6 import java.util.Iterator;
     7 import java.util.TreeSet;
     8 
     9 public class TreeSetDemo
    10 {
    11     public static void main(String[] args)
    12     {
    13         treeSetDemo();
    14     }
    15     
    16     public static void treeSetDemo()
    17     {
    18         TreeSet ts = new TreeSet();
    19         ts.add(new Student("t1",11));
    20         // 如果Student类没有实现Comparable接口,多添加下面一条数据就抛异常
    21         // 因为这个类中的数据没有可比较性
    22         ts.add(new Student("t2",12));
    23         ts.add(new Student("t3",13));
    24         
    25         Iterator it = ts.iterator();
    26         while(it.hasNext())
    27         {
    28             Student stu = (Student)it.next();
    29             System.out.println("name:" + stu.getName() + ",age:" + stu.getAge());
    30         }
    31         
    32     }
    33     
    34 }
    35 
    36 // 该接口强制让学生具备比较性
    37 class Student implements Comparable
    38 {
    39     private String name;
    40     private int age;
    41     
    42     public Student(String name, int age)
    43     {
    44         this.name = name;
    45         this.age = age;
    46     }
    47     
    48     @Override
    49     public int compareTo(Object obj)
    50     {
    51         if(!(obj instanceof Student))
    52         {
    53             throw new RuntimeException("不是Student类");
    54         }
    55         
    56         Student stu = (Student)obj;
    57         
    58         if(this.age > stu.age)
    59             return 1;  // 只要返回正数即可
    60         if(this.age == stu.age)
    61         {
    62             // String类型本身也实现了Comparable接口
    63             return this.name.compareTo(stu.name);
    64         }
    65             
    66         return -1;  // 只要返回负数即可
    67     }
    68 
    69     public String getName()
    70     {
    71         return name;
    72     }
    73     
    74     public void setName(String name)
    75     {
    76         this.name = name;
    77     }
    78     
    79     public int getAge()
    80     {
    81         return age;
    82     }
    83 
    84     public void setAge(int age)
    85     {
    86         this.age = age;
    87     }
    88 }
      1 /**
      2  * 功能:Comparator的使用
      3  */
      4 package collection;
      5 
      6 import java.util.Comparator;
      7 import java.util.Iterator;
      8 import java.util.TreeSet;
      9 
     10 public class TreeSetDemo2
     11 {
     12     public static void main(String[] args)
     13     {
     14         treeSerDemo2();
     15     }
     16     
     17     public static void treeSerDemo2()
     18     {
     19         TreeSet ts = new TreeSet(new MyComparator());
     20         ts.add(new Student2("t1",11));
     21         // 如果Student类没有实现Comparator接口,多添加下面一条数据就抛异常
     22         // 因为这个类中的数据没有可比较性
     23         ts.add(new Student2("t2",12));
     24         ts.add(new Student2("t3",13));
     25         
     26         Iterator it = ts.iterator();
     27         while(it.hasNext())
     28         {
     29             Student2 stu = (Student2)it.next();
     30             System.out.println("name:" + stu.getName() + ",age:" + stu.getAge());
     31         }
     32     }
     33 }
     34 
     35 class MyComparator implements Comparator
     36 {
     37 
     38     @Override
     39     public int compare(Object o1, Object o2)
     40     {
     41        if(!(o1 instanceof Student2) || !(o2 instanceof Student2))
     42         {
     43             try
     44             {
     45                 throw new Exception("传入的比较对象不是要求的比较对象");
     46             } catch (Exception e)
     47             {
     48                 e.printStackTrace();
     49             }
     50 }
     51 
     52         Student2 stu1 = (Student2)o1;
     53         Student2 stu2 = (Student2)o2;
     54         
     55         int num = stu1.getName().compareTo(stu2.getName());
     56         if(num == 0)
     57         {
     58             // int型比较方法一
     59             // 封装成Interger对象进行比较
     60             // return new Integer(stu1.getAge()).compareTo(new Integer(stu2.getAge()));
     61             
     62             // int型比较方法二
     63             if(stu1.getAge() > stu2.getAge())
     64                 return 1;
     65             if(stu1.getAge() == stu2.getAge())
     66                 return 0;
     67             return -1;
     68         }
     69         
     70         return num;
     71     }
     72     
     73 }
     74 
     75 class Student2
     76 {
     77     private String name;
     78     private int age;
     79     
     80     public Student2(String name, int age)
     81     {
     82         this.name = name;
     83         this.age = age;
     84     }
     85     
     86     public String getName()
     87     {
     88         return name;
     89     }
     90     public void setName(String name)
     91     {
     92         this.name = name;
     93     }
     94     public int getAge()
     95     {
     96         return age;
     97     }
     98     public void setAge(int age)
     99     {
    100         this.age = age;
    101     }
    102 }
     1 /**
     2  * 功能:比较字符串长度是否相等
     3  */
     4 package collection;
     5 
     6 import java.util.Comparator;
     7 import java.util.Iterator;
     8 import java.util.TreeSet;
     9 
    10 public class TreeSetDemo3
    11 {
    12     public static void main(String[] args)
    13     {
    14         TreeSet ts = new TreeSet(new MyStrComparator());
    15         ts.add("asd");
    16         ts.add("wer");
    17          ts.add("qaz");
    18         ts.add("qwerty");
    19         ts.add("df");
    20         
    21         Iterator it = ts.iterator();
    22         while(it.hasNext())
    23         {
    24             System.out.println(it.next());
    25         }
    26     }
    27 }
    28 
    29 class MyStrComparator implements Comparator
    30 {
    31     @Override
    32     public int compare(Object o1, Object o2)
    33     {
    34         String s1 = (String)o1;
    35         String s2 = (String)o2;
    36         
    37         int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
    38         if(num == 0)
    39         {
    40             return s1.compareTo(s2);
    41         }
    42         return num;
    43     }
    44     
    45 }
     1 /**
     2  * 功能:匿名内部类的使用
     3  */
     4 package collection;
     5 
     6 import java.util.Comparator;
     7 import java.util.Iterator;
     8 import java.util.TreeSet;
     9 
    10 public class TreeSetDemo4
    11 {
    12     public static void main(String[] args)
    13     {
    14         TreeSet ts = new TreeSet(new Comparator(){
    15             @Override
    16             public int compare(Object o1, Object o2)
    17             {
    18                 String s1 = (String)o1;
    19                 String s2 = (String)o2;
    20                 
    21                 int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
    22                 if(num == 0)
    23                 {
    24                     return s1.compareTo(s2);
    25                 }
    26                 return num;
    27             }});
    28         
    29         ts.add("asd");
    30         ts.add("wer");
    31         ts.add("qwerty");
    32         ts.add("df");
    33         
    34         Iterator it = ts.iterator();
    35         while(it.hasNext())
    36         {
    37             System.out.println(it.next());
    38         }
    39     }
    40 }
     1 /**
     2  * 功能:泛型的使用
     3  */
     4 package collection;
     5 
     6 import java.util.ArrayList;
     7 import java.util.Iterator;
     8 
     9 public class GenericDemo
    10 {
    11     public static void main(String[] args)
    12     {
    13         genericDemo2();
    14     }
    15     
    16     // 没有使用泛型
    17     public static void genericDemo()
    18     {
    19         ArrayList al = new ArrayList();
    20         al.add("qwe");
    21         // 上面添加的字符串,下面添加的是int,迭代时肯定会报类型转换异常
    22         al.add(4);
    23         
    24         Iterator it = al.iterator();
    25         while(it.hasNext())
    26         {
    27             // 需要类型转换
    28             // 此处在运行时会报类型转换异常
    29             // 在编译时不会报异常
    30             String s = (String)it.next();
    31             System.out.println(s + ":" + s.length());
    32         }
    33     }
    34     
    35     // JDK1.5之后使用泛型
    36     // 解决安全问题
    37     public static void genericDemo2()
    38     {
    39         // 指定只添加String类型数据
    40         ArrayList<String> al = new ArrayList<String>();
    41         al.add("qwe");
    42         // 编译时下面这条语句就报错了
    43         // al.add(4);
    44         
    45         // 迭代器也通过泛型指定类型
    46         // 后续就不需要进行内外部转换了
    47         Iterator<String> it = al.iterator();
    48         while(it.hasNext())
    49         {
    50             String s = it.next();
    51             System.out.println(s + ":" + s.length());
    52         }
    53     }
    54 }
     1 /**
     2  * 功能:定义泛型类
     3  */
     4 package collection;
     5 
     6 public class GenericClass
     7 {
     8     public static void main(String[] args)
     9     {
    10         Tool tool = new Tool();
    11         tool.setObject(new Teacher());
    12         // 没用泛型之前,需要进行强转
    13         Teacher teacher = (Teacher) tool.getObject();
    14         System.out.println(teacher);
    15         
    16         Util<Doctor> util = new Util<Doctor>();
    17         util.setObject(new Doctor());
    18         // 使用泛型之后,不需要进行强转
    19         Doctor doctor = util.getObject();
    20         System.out.println(doctor);
    21     }
    22 }
    23 
    24 // 没用泛型之前
    25 class Tool
    26 {
    27     private Object object;
    28 
    29     public Object getObject()
    30     {
    31         return object;
    32     }
    33 
    34     public void setObject(Object object)
    35     {
    36         this.object = object;
    37     }
    38     
    39 }
    40 
    41 // 用了泛型之后
    42 class Util<Q>
    43 {
    44     private Q object;
    45     
    46     public void setObject(Q q)
    47     {
    48         this.object = q;
    49     }
    50     public Q getObject()
    51     {
    52         return object;
    53     }
    54     
    55 }
    56 
    57 class Teacher
    58 {
    59     
    60 }
    61 
    62 class Doctor
    63 {
    64     
    65 }
     1 /**
     2  * 功能:将泛型定义在方法上
     3  */
     4 package collection;
     5 
     6 public class GenericDemo2
     7 {
     8     public static void main(String[] args)
     9     {
    10         Utils ut = new Utils();
    11         // 可以打印字符串
    12         ut.show("qwe");
    13         // 可以打印int类型
    14         ut.show(12);
    15     }
    16 }
    17 
    18 class Utils
    19 {
    20     public <T> void show(T t)
    21     {
    22         System.out.println("show:" + t);
    23     }
    24     
    25     public <Q> void print(Q q)
    26     {
    27         System.out.println("print:" + q);
    28     }
    29 }
     1 /**
     2  * 功能:类和方法上都定义泛型
     3  */
     4 package collection;
     5 
     6 public class GenericDemo3
     7 {
     8     public static void main(String[] args)
     9     {
    10         Tools<String> tl = new Tools<String>();
    11         // 只能打印String类型
    12         tl.show("qwer");
    13         // 打印其他类型报错
    14         // tl.show(123);
    15         
    16         // 可以打印String类型
    17         tl.print("qwe");
    18         // 也可以打印其他类型
    19         tl.print(123);
    20         
    21         Tools.display("qwe");
    22         Tools.display(123);
    23     }
    24 }
    25 
    26 class Tools<T>
    27 {
    28     // 这个方法的类型是跟着对象(类型T)走的
    29     public void show(T t)
    30     {
    31         System.out.println("show:" + t);
    32     }
    33     
    34     // 这个方法的类型是跟着Q走的
    35     public <Q> void print(Q q)
    36     {
    37         System.out.println("print:" + q);
    38     }
    39     
    40     // 泛型定义在返回值的前面,修饰符的后面
    41     public static <W> void display(W w)
    42     {
    43         System.out.println("display:" + w);
    44     }
    45 }
     1 /**
     2  * 功能:接口上定义泛型
     3  */
     4 package collection;
     5 
     6 public class GenericDemo4
     7 {
     8     public static void main(String[] args)
     9     {
    10         InterImpl ii = new InterImpl();
    11         ii.show("qwe");
    12         
    13         InterImpl2<String> ii2 = new InterImpl2<String>();
    14         ii2.show("asd");
    15         
    16         InterImpl2<Integer> ii3 = new InterImpl2<Integer>();
    17         ii3.show(123);
    18     }
    19 }
    20 
    21 interface Inter<T>
    22 {
    23     public void show(T t);
    24 }
    25 
    26 class InterImpl implements Inter<String>
    27 {
    28     @Override
    29     public void show(String t)
    30     {
    31         System.out.println("show:" + t);
    32     }
    33 }
    34 
    35 class InterImpl2<T> implements Inter<T>
    36 {
    37     @Override
    38     public void show(T t)
    39     {
    40         System.out.println("show:" + t);
    41     }
    42 }
     1 /**
     2  * 功能:泛型的高级特性
     3  */
     4 package collection;
     5 
     6 import java.util.ArrayList;
     7 import java.util.Iterator;
     8 
     9 public class GenericDemo5
    10 {
    11     public static void main(String[] args)
    12     {
    13         ArrayList<String> al1 = new ArrayList<String>();
    14         al1.add("qwe");
    15         al1.add("asd");
    16         al1.add("zxc");
    17         
    18         ArrayList<Integer> al2 = new ArrayList<Integer>();
    19         al2.add(123);
    20         al2.add(456);
    21         al2.add(789);
    22         
    23         demo(al1);
    24         demo(al2);
    25         
    26         demo2(al1);
    27         demo2(al2);
    28     }
    29     
    30     // 不清楚是什么类型时候,可以用?代替
    31     public static void demo(ArrayList<?> al)
    32     {
    33         Iterator<?> it = al.iterator();
    34         while(it.hasNext())
    35         {
    36             System.out.println("al:" + it.next());
    37             // 以下使用length()是错误的
    38             // 因为不知道是什么类型,所以不能使用某一具体类型的特有方法
    39             // System.out.println(it.next().length());
    40         }
    41     }
    42     
    43     // 也可以换成T,但T代表了某一个具体类型
    44     // 操作方面有一点变化
    45     public static <T> void demo2(ArrayList<T> al)
    46     {
    47         Iterator<T> it = al.iterator();
    48         while(it.hasNext())
    49         {
    50             System.out.println("al:" + it.next());
    51             // 使用了某一具体类型之后
    52             // 可以用这个具体类型来接收迭代出来的元素,并进行其他具体操作
    53             // T t = it.next();
    54             // System.out.println("al:" + t);
    55         }
    56     }
    57 }
      1 /**
      2  * 功能:泛型的高级特性2
      3  */
      4 package collection;
      5 
      6 import java.util.ArrayList;
      7 import java.util.Iterator;
      8 
      9 public class GenericDemo6
     10 {
     11     public static void main(String[] args)
     12     {
     13         ArrayList<Person> al = new ArrayList<Person>();
     14         al.add(new Person("qwe"));
     15         al.add(new Person("asd"));
     16         al.add(new Person("zxc"));
     17         
     18         ArrayList<Worker> al2 = new ArrayList<Worker>();
     19         al2.add(new Worker("qwe"));
     20         al2.add(new Worker("asd"));
     21         al2.add(new Worker("zxc"));
     22         
     23         ArrayList<Student6> al3 = new ArrayList<Student6>();
     24         al3.add(new Student6("qwe"));
     25         al3.add(new Student6("asd"));
     26         al3.add(new Student6("zxc"));
     27         
     28         // 正确
     29         demo(al);
     30         // 错误,以下两种情况都是不允许的,左右不匹配
     31         // ArrayList<Person> al2 = new ArrayList<Student>();
     32         // ArrayList<Student> al2 = new ArrayList<Person>();
     33         // demo(al2);
     34         
     35         demo3(al2);
     36         demo3(al);
     37         // Student6类不是Person类的子类,所以下面写法错误
     38         // demo3(al3);
     39         
     40         demo4(al);
     41         demo4(al2);
     42         // Student6类不是Worker类的父类,所以下面写法错误
     43         // demo4(al3);
     44     }
     45     
     46     public static void demo(ArrayList<Person> al)
     47     {
     48         Iterator<Person> it = al.iterator();
     49         while(it.hasNext())
     50         {
     51             Person p = it.next();
     52             System.out.println("name:" + p.getName());
     53         }
     54     }
     55     
     56     // 打印出所有类型
     57     public static void demo2(ArrayList<?> al)
     58     {
     59         Iterator<?> it = al.iterator();
     60         while(it.hasNext())
     61         {
     62             System.out.println(it.next());
     63         }
     64     }
     65     
     66     // 打印出指定的范围:泛型限定
     67     // 只打印Person和它的子类
     68     public static void demo3(ArrayList<? extends Person> al)
     69     {
     70         Iterator<? extends Person> it = al.iterator();
     71         while(it.hasNext())
     72         {
     73             System.out.println(it.next().getName());
     74         }
     75     }
     76     
     77     public static void demo4(ArrayList<? super Worker> al)
     78     {
     79         Iterator<? super Worker> it = al.iterator();
     80         while(it.hasNext())
     81         {
     82             System.out.println(it.next());
     83         }
     84     }
     85 }
     86 
     87 class Person
     88 {
     89     private String name;
     90     
     91     public Person(String name)
     92     {
     93         this.name = name;
     94     }
     95     
     96     public String getName()
     97     {
     98         return name;
     99     }
    100     
    101     public void setName(String name)
    102     {
    103         this.name = name;
    104     }
    105 }
    106 
    107 class Worker extends Person
    108 {
    109     public Worker(String name)
    110     {
    111         super(name);
    112     }
    113 }
    114 
    115 class Student6
    116 {
    117     private String name;
    118     public Student6(String name)
    119     {
    120         this.name = name;
    121     }
    122     public String getName()
    123     {
    124         return name;
    125     }
    126     public void setName(String name)
    127     {
    128         this.name = name;
    129     }
    130 }
      1 /**
      2  * 功能:泛型的高级应用3
      3  */
      4 package collection;
      5 
      6 import java.util.Comparator;
      7 import java.util.Iterator;
      8 import java.util.TreeSet;
      9 
     10 public class GenericDemo7
     11 {
     12     public static void main(String[] args)
     13     {
     14         // 使用Studnet3类的构造器
     15         // TreeSet<Student3> tr = new TreeSet<Student3>(new StuComparator());
     16         // 使用通用的比较器(父类的比较器)
     17         TreeSet<Student3> tr = new TreeSet<Student3>(new MyComparator2());
     18         tr.add(new Student3("stu4"));
     19         tr.add(new Student3("stu2"));
     20         tr.add(new Student3("stu3"));
     21         
     22         Iterator<Student3> it = tr.iterator();
     23         while(it.hasNext())
     24         {
     25             System.out.println("tr:" + it.next().getName());
     26         }
     27         
     28         // 使用Worker2类的构造器
     29         // TreeSet<Worker2> tr2 = new TreeSet<Worker2>(new WorComparator());
     30         // 使用通用的比较器(父类的比较器)
     31         TreeSet<Worker2> tr2 = new TreeSet<Worker2>(new MyComparator2());
     32         tr2.add(new Worker2("wor1"));
     33         tr2.add(new Worker2("wor5"));
     34         tr2.add(new Worker2("wor3"));
     35         
     36         Iterator<Worker2> it2 = tr2.iterator();
     37         while(it2.hasNext())
     38         {
     39             System.out.println("tr:" + it2.next().getName());
     40         }
     41     }
     42 }
     43 
     44 // Student3类的比较器,分开写很麻烦
     45 class StuComparator implements Comparator<Student3>
     46 {
     47     @Override
     48     public int compare(Student3 o1, Student3 o2)
     49     {
     50         return o1.getName().compareTo(o2.getName());
     51     }
     52 }
     53 
     54 // Worker2类的比较器,分开写很麻烦
     55 class WorComparator implements Comparator<Worker2>
     56 {
     57     @Override
     58     public int compare(Worker2 o1, Worker2 o2)
     59     {
     60         return o1.getName().compareTo(o2.getName());
     61     }
     62 }
     63 
     64 // Comparator<? super E>
     65 class MyComparator2 implements Comparator<Person2>
     66 {
     67     @Override
     68     public int compare(Person2 o1, Person2 o2)
     69     {
     70         return o1.getName().compareTo(o2.getName());
     71     }
     72 }
     73 
     74 class Person2
     75 {
     76     private String name;
     77     
     78     public Person2(String name)
     79     {
     80         this.name = name;
     81     }
     82 
     83     public String getName()
     84     {
     85         return name;
     86     }
     87 
     88     public void setName(String name)
     89     {
     90         this.name = name;
     91     }
     92     
     93 }
     94 
     95 class Student3 extends Person2
     96 {
     97     // private String name;
     98     public Student3(String name)
     99     {
    100         super(name);
    101     }
    102 }
    103 
    104 class Worker2 extends Person2
    105 {
    106     public Worker2(String name)
    107     {
    108         super(name);
    109     }
    110 }
     1 /**
     2  * 功能:获取Map集合数据的两种方式
     3  */
     4 package collection;
     5 
     6 import java.util.HashMap;
     7 import java.util.Iterator;
     8 import java.util.Map;
     9 import java.util.Set;
    10 
    11 public class MapDemo
    12 {
    13     public static void main(String[] args)
    14     {
    15         keySet();
    16         entrySet();
    17     }
    18     
    19     // 方法一:通过keySet()来获取
    20     public static void keySet()
    21     {
    22         HashMap<String,String> map = new HashMap<String,String>();
    23         map.put("01", "zhangsan");
    24         map.put("05", "lisi");
    25         map.put("03", "wangwu");
    26         
    27         Set<String> keySet = map.keySet();
    28         
    29         Iterator<String> it = keySet.iterator();
    30         while(it.hasNext())
    31         {
    32             String key = it.next();
    33             String value = map.get(key);
    34             System.out.println("key:" + key + ",value:" + value);
    35         }
    36     }
    37     
    38     // 方法二:通过entrySet()来获取
    39     public static void entrySet()
    40     {
    41         HashMap<String,String> map = new HashMap<String,String>();
    42         map.put("01", "zhangsan");
    43         map.put("05", "lisi");
    44         map.put("03", "wangwu");
    45         
    46         Set<Map.Entry<String, String>> entrySet = map.entrySet();
    47         Iterator<Map.Entry<String, String>> it = entrySet.iterator();
    48         while(it.hasNext())
    49         {
    50             Map.Entry<String, String> me = it.next();
    51             String key = me.getKey();
    52             String value = me.getValue();
    53             System.out.println("key:" + key + ",value:" + value);
    54         }
    55     }
    56 }
     1 /**
     2  * 功能:HashMap集合的扩展
     3  */
     4 package collection;
     5 
     6 import java.util.HashMap;
     7 import java.util.Iterator;
     8 import java.util.Set;
     9 
    10 public class MapDemo2
    11 {
    12     public static void main(String[] args)
    13     {
    14         HashMap<String,String> yure = new HashMap<String,String>();
    15         yure.put("01", "zhangsan");
    16         yure.put("02", "lisi");
    17         
    18         HashMap<String,String> jiuye = new HashMap<String,String>();
    19         jiuye.put("03", "wangwu");
    20         jiuye.put("04", "zhaoliu");
    21         
    22         HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>();
    23         czbk.put("yure", yure);
    24         czbk.put("jiuye", jiuye);
    25         
    26         Set<String> map = czbk.keySet();
    27         Iterator<String> it = map.iterator();
    28         while(it.hasNext())
    29         {
    30             String key = it.next();
    31             HashMap<String,String> values = czbk.get(key);
    32             System.out.println("key:" + key + "values:" + values);
    33             getStuInfo(values);
    34         }
    35         
    36         // getStuInfo(jiuye);
    37     }
    38     
    39     public static void getStuInfo(HashMap<String,String> room)
    40     {
    41         Set<String> map = room.keySet();
    42         Iterator<String> it = map.iterator();
    43         while(it.hasNext())
    44         {
    45             String key = it.next();
    46             String value = room.get(key);
    47             System.out.println("id:" + key + ",value:" + value);
    48         }
    49     }
    50 }
     1 /**
     2  * 功能:JDK1.5新特性,可变参数
     3  */
     4 package collection;
     5 
     6 public class CollectionDemo
     7 {
     8     public static void main(String[] args)
     9     {
    10         syso(1,2,3,4,5);
    11         syso(3,4);
    12     }
    13     
    14     public static void syso(int... arr)
    15     {
    16         for(int i=0;i<arr.length;i++)
    17         {
    18             System.out.println(i);
    19         }
    20     }
    21 }
     1 /**
     2  * 功能:JDK1.5新特性,静态导入
     3  */
     4 package collection;
     5 
     6 import java.util.Arrays;
     7 
     8 // 实现静态导入,导入的是Arrays这个类中的所有静态成员
     9 import static java.util.Arrays.*;
    10 
    11 public class CollectionDemo2
    12 {
    13     public static void main(String[] args)
    14     {
    15         int[] arr = {6,2,8};
    16         // 原来是这样写的
    17         // int index = Arrays.binarySearch(arr, 2);
    18         // 现在可以这样写
    19         int index = binarySearch(arr, 2);
    20         
    21         System.out.println(index);
    22         
    23     }
    24 }
  • 相关阅读:
    linux安装及入门
    20165103学习基础和C语言基础调查
    20165103 我期望的师生关系
    自旋锁,偏向锁,轻量级锁 和 重量级锁
    volatile的使用及其原理
    (PASS)什么是原子性和原子性操作?
    Linux操作系统 和 Windows操作系统 的区别
    Linux常用命令大全(很全面)
    CAS机制总结
    CAS -- ABA问题的解决方案
  • 原文地址:https://www.cnblogs.com/kehuaihan/p/6759988.html
Copyright © 2011-2022 走看看