JAVA学习打卡第九天——集合框架

JAVA学习打卡第九天

学习视频

集合概念

  • 概念:对象的容器,定义了对多个对象进行操作的常用方法,可实现数组的功能
  • 和数组的区别:
    • 数组长度固定,集合长度不固定
    • 数组可以存储基本类型和引用类型,集合只能存储引用类型

Collection体系

  • Collection体系集合

在这里插入图片描述

  • Collection接口:该体系结构的根接口,代表一组对象,称为”集合“

  • List接口特点:

    • 有序
    • 有下标
    • 元素可重复
  • Set接口

    • 无序
    • 无下标
    • 元素不能重复

Collection接口

  • 特点:代表一组任意类型的对象,无序、无下标、不能重复

  • 方法:

    • boolean add(Object obj):添加一个对象

    • boolean addAll(Collection c):将一个集合中的所有对象添加到此集合中

    • void clear():清空此集合中的所有对象

    • boolean contains(Object o):检查此集合中是否包含o对象

    • boolean isEmpty():判断此集合是否为空

    • boolean remove(Object o):在此集合中移除o对象

    • int size():返回此集合中的元素个数

    • Object[] toArray():将此集合转换成数组

    • 示例(String类型)

      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Iterator;
      
      public class Demo_01 {
          public static void main(String[] args) {
              //创建集合
              Collection collection = new ArrayList();
              //添加元素
              System.out.println("==========add==========");
              collection.add("苹果");
              collection.add("西瓜");
              collection.add("榴莲");
              System.out.println("元素个数:" + collection.size());
              System.out.println("集合内容:" + collection.toString());
              //删除元素
              System.out.println("==========remove==========");
              collection.remove("榴莲");
              System.out.println("元素个数:" + collection.size());
              System.out.println("集合内容:" + collection.toString());
              //清空
              //System.out.println("==========clear==========");
              //collection.clear();
              //System.out.println("元素个数:" + collection.size());
              //System.out.println("集合内容:" + collection.toString());
              //遍历元素
              //(1)增强for
              System.out.println("==========(1)增强for==========");
              for (Object o : collection) {
                  System.out.println(o);
              }
              System.out.println("==========(2)迭代器==========");
              Iterator iterator = collection.iterator();
              while (iterator.hasNext()) {
                  String s = (String)iterator.next();
                  System.out.println(s);
                  iterator.remove();
              }
              System.out.println("遍历后剩余元素数:" + collection.size());
              //判断
              System.out.println("==========contains==========");
              System.out.println(collection.contains("西瓜"));
          }
      }
      

      在这里插入图片描述

    • 示例(Student类)

      public class Student {
          private String name;
          private int age;
          public Student() {
      
          }
          public Student(String name, int age) {
              super();
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return this.name;
          }
          public void setName(String name) {
              this.name = name;
          }
          public int getAge() {
              return this.age;
          }
          public void setAge(int age) {
              this.age = age;
          }
          public String toString() {
              return "Student [name:" + this.name + ";age:" + this.age + "]";
          }
      }
      
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Iterator;
      
      public class test {
          public static void main(String[] args) {
              //新建Collection对象
              Collection collection = new ArrayList();
              //实例化学生对象
              Student student_1 = new Student("s1", 20);
              Student student_2 = new Student("s2", 21);
              Student student_3 = new Student("s3", 19);
              //添加数据
              System.out.println("==========add==========");
              collection.add(student_1);
              collection.add(student_2);
              collection.add(student_3);
              System.out.println("元素个数:" + collection.size());
              System.out.println(collection.toString());
              //删除数据
              System.out.println("==========remove==========");
              collection.remove(student_1);
              System.out.println("元素个数:" + collection.size());
              System.out.println(collection.toString());
              //遍历
              //(1)增强for
              System.out.println("==========(1)增强for==========");
              for (Object o : collection) {
                  System.out.println(o);
              }
              //(2)迭代器
              System.out.println("==========(2)迭代器==========");
              Iterator it = collection.iterator();
              while (it.hasNext()) {
                  Student s = (Student) it.next();
                  System.out.println(s.toString());
              }
              //判断
              System.out.println("==========contains==========");
              System.out.println(collection.contains(student_2));
              System.out.println(collection.contains(new Student("s2", 21)));
          }
      }
      

      在这里插入图片描述

List接口与实现类

  • 特点:

    • 有序:元素存储有顺序
    • 有下标:可通过下标访问
    • 可重复:元素可以重复存在
  • 方法:

    • void add(int index, Object 0):在指定位置(index)插入对象o

    • boolean addAll(int index, Collection c):将一个集合中的元素添加到此集合中的index位置

    • Object get(int index):返回集合中指定位置的元素

    • List subList(int fromIndex, int toIndex):返回fromIndex到toIndex之间的集合元素

    • 实例(String类)

      import java.util.ArrayList;
      import java.util.Iterator;
      import java.util.List;
      import java.util.ListIterator;
      
      public class String_List {
          public static void main(String[] args) {
              //创建集合对象
              List list = new ArrayList();
              //添加元素
              System.out.println("==========add==========");
              list.add("苹果");
              list.add("小米");
              list.add(0, "华为");
              System.out.println("元素数:" + list.size());
              System.out.println(list.toString());
              //删除元素
              System.out.println("==========remove==========");
              list.remove(0);
              System.out.println(list.size());
              System.out.println(list.toString());
              //遍历
              //(1)for
              System.out.println("==========(1)for==========");
              for(int i = 0;i < list.size();i++) {
                  System.out.println(list.get(i));
              }
              //(2)增强for
              System.out.println("==========(2)增强for==========");
              for (Object o : list) {
                  System.out.println(o);
              }
              //(3)迭代器
              System.out.println("==========(3)迭代器:iterator==========");
              Iterator it = list.iterator();
              while(it.hasNext()) {
                  Object ob = it.next();
                  System.out.println(ob);
              }
              //(4)列表迭代器
              System.out.println("==========(4)列表迭代器:listIterator==========");
              ListIterator lit = list.listIterator();
              System.out.println("从前往后");
              while (lit.hasNext()) {
                  System.out.println(lit.nextIndex() + ":" + lit.next());
              }
              System.out.println("从后往前");
              while (lit.hasPrevious()) {
                  System.out.println(lit.previousIndex() + ":" + lit.previous());
              }
              //判断
              System.out.println("==========contains==========");
              System.out.println("判断“苹果”是否在集合中:" + list.contains("苹果"));
              System.out.println("判断集合是否为空:" + list.isEmpty());
              //获取
              System.out.println("==========indexOf==========");
              System.out.println("“小米”在集合中的位置:" + list.indexOf("小米"));
          }
      }
      

      在这里插入图片描述

    • 实例(数字数据)

      import java.util.ArrayList;
      import java.util.List;
      
      public class number_list {
          public static void main(String[] args) {
              //创建集合
              List list = new ArrayList();
              //添加数字数据
              System.out.println("==========添加数字数据==========");
              list.add(20);
              list.add(30);
              list.add(40);
              list.add(50);
              list.add(60);
              System.out.println("元素个数:" + list.size());
              System.out.println("元素:" + list.toString());
              //删除数据
              //以下三种方式效果一样
              System.out.println("==========删除数据==========");
              list.remove((Object)20);
              //list.remove(new Integer(20));---------->注意要在缓冲区之内
              //list.remove(0);
              System.out.println("元素个数:" + list.size());
              System.out.println("元素:" + list.toString());
              //返回子集合
              System.out.println("==========返回子集合:1~2==========");
              List lst = list.subList(1, 3);
              System.out.println("子集合元素个数:" + lst.size());
              System.out.println("子集合元素:" + lst.toString());
          }
      }
      

      在这里插入图片描述

  • List实现类

    • ArrayList【重点】:

      • 数组结构实现,查询快、增删慢

      • JDK1.2版本后,运行效率快、线程不安全

        java.util.ArrayList;
        import java.util.Iterator;
        import java.util.ListIterator;
        
        public class ArrayList_test {
            public static void main(String[] args) {
                //创建集合
                ArrayList arrayList = new ArrayList();
                //创建学生对象
                Student s_1 = new Student("s1", 18);
                Student s_2 = new Student("s2", 19);
                Student s_3 = new Student("s3", 20);
                //添加元素
                System.out.println("==========add==========");
                arrayList.add(s_1);
                arrayList.add(s_2);
                arrayList.add(s_3);
                System.out.println("元素个数:" + arrayList.size());
                System.out.println("元素:" + arrayList.toString());
                //删除元素
                System.out.println("==========remove==========");
                //arrayList.remove(s_1);
                arrayList.remove(new Student("s1", 18));//---->注意一定要改写equals方法
                System.out.println("元素个数:" + arrayList.size());
                System.out.println("元素:" + arrayList.toString());
                //遍历
                System.out.println("==========(1)迭代器:iterator==========");
                Iterator it = arrayList.iterator();
                while (it.hasNext()) {
                    System.out.println(it.next());
                }
                System.out.println("==========(2)列表迭代器:listIterator==========");
                ListIterator lis = arrayList.listIterator();
                System.out.println("从前往后");
                while (lis.hasNext()) {
                    System.out.println(lis.next());
                }
                System.out.println("从后往前");
                while (lis.hasPrevious()) {
                    System.out.println(lis.previous());
                }
                //判断
                System.out.println("==========contains==========");
                System.out.print("new Student(\"s2\", 19)是否在集合中:");
                System.out.println(arrayList.contains(new Student("s2", 19)));//--->一定要重写equals
                System.out.println("集合是否是空的:" + arrayList.isEmpty());
                //查找
                System.out.println("new Student(\"s3\", 20)在集合中位置:" + arrayList.indexOf(new Student("s3", 20)));
            }
        }
        

        在这里插入图片描述

      • 源码分析

    • Vector:

      • 数组结构实现,查询快、增删慢

      • JDK1.0版本,运行效率慢、线程安全

        import java.util.Enumeration;
        import java.util.Vector;
        
        public class Vector_test {
            public static void main(String[] args) {
                //创建集合
                Vector vector = new Vector();
                //添加元素
                System.out.println("==========add==========");
                vector.add("草莓");
                vector.add("芒果");
                vector.add("西瓜");
                System.out.println("元素个数:" + vector.size());
                System.out.println("元素个数:" + vector.toString());
                //删除
                System.out.println("==========remove==========");
                //vector.remove(0);
                vector.remove("草莓");
                System.out.println("元素个数:" + vector.size());
                System.out.println("元素个数:" + vector.toString());
                //遍历
                //枚举器
                System.out.println("==========遍历:枚举器:Enumeration==========");
                Enumeration en = vector.elements();
                while (en.hasMoreElements()) {
                    String s = (String) en.nextElement();
                    System.out.println(s.toString());
                }
                //判断
                System.out.println("==========contains、isEmpty==========");
                System.out.println("判断“西瓜”是否在集合中:" + vector.contains("西瓜"));
                System.out.println("判断集合是否为空:" + vector.isEmpty());
                //其他方法
                System.out.println("==========get==========");
                System.out.println("0号位的元素:" + vector.get(0));
            }
        }
        

        在这里插入图片描述

    • LinkedList:

      • 链表结构实现,增删快,查询慢

        import java.util.Iterator;
        import java.util.LinkedList;
        import java.util.ListIterator;
        
        public class LinkedList_test {
            public static void main(String[] args) {
                LinkedList linkedList = new LinkedList();
                //创建学生对象
                Student s_1 = new Student("s1", 18);
                Student s_2 = new Student("s2", 19);
                Student s_3 = new Student("s3", 20);
                //添加元素
                System.out.println("==========add==========");
                linkedList.add(s_1);
                linkedList.add(s_2);
                linkedList.add(s_3);
                linkedList.add(s_3);
                System.out.println("元素个数:" + linkedList.size());
                System.out.println("元素:" + linkedList.toString());
                //删除元素
                System.out.println("==========remove==========");
                //linkedList.remove(s_1);
                linkedList.remove(new Student("s3", 20));//-------->必须重写equals
                System.out.println("元素个数:" + linkedList.size());
                System.out.println("元素:" + linkedList.toString());
                //遍历
                System.out.println("==========(1)for==========");
                for (int i = 0; i < linkedList.size(); i++) {
                    System.out.println(linkedList.get(i));
                }
                System.out.println("==========(2)增强for==========");
                for (Object o : linkedList) {
                    Student s = (Student) o;
                    System.out.println(s);
                }
                System.out.println("==========(3)迭代器:iterator==========");
                Iterator it = linkedList.iterator();
                while (it.hasNext()) {
                    System.out.println(it.next());
                }
                System.out.println("==========(4)列表迭代器:listiterator==========");
                ListIterator lis = linkedList.listIterator();
                while (lis.hasNext()) {
                    System.out.println(lis.next());
                }
                //判断
                System.out.println("==========contains、isEmpty==========");
                System.out.println("判断s_1是否在集合中:" + linkedList.contains(s_1));
                System.out.println("判断集合是否为空:" + linkedList.isEmpty());
            }
        }
        

        在这里插入图片描述

      • LinkedList源码分析

泛型和工具类

  • Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递

  • 常见形式有泛型类、泛型接口、泛型方法

  • 语法

    <T,…> T称为类型占位符,表示一种引用类型

  • 好处

    • 提高代码的重用性
    • 防止类型转换异常,提高代码的安全性

泛型类

  • 泛型只能使用引用类型

  • 不同泛型对象之间不能相互赋值

    public class genericClass<T> {//T是类型占位符,表示一种引用类型,如果编写多个,使用逗号隔开
        //使用泛型
        //创建变量
        T t;
        //泛型作为方法的参数
        public void show(T t) {
            System.out.println(t);
        }
        //泛型作为方法的返回值
        public T getT() {
            return t;
        }
    }
    
    public class test {
        public static void main(String[] args) {
            //使用泛型类创建对象
            genericClass<String> genericClass = new genericClass<String>();
            genericClass.t = "hello";
            genericClass.show("hahahaha");
            String s = genericClass.getT();
    
            genericClass<Integer> genericClass_2 = new genericClass<>();
            genericClass_2.t = 10;
            genericClass_2.show(20);
            Integer integer = genericClass_2.getT();
        }
    }
    

泛型接口

  • 不能创建泛型静态常量

  • 两种实现方法

    • 接口

      public interface genericInterface<T> {
          String name = "xianyun";
          T server(T t);
      }
      
    • 第一种

      public class myInterface implements genericInterface<String> {
          public String server(String t) {
              System.out.println(t);
              return null;
          }
      }
      
      public class test {
          public static void main(String[] args) {
              myInterface mi = new myInterface();
              mi.server("hahahaha");
          }
      }
      
    • 第二种

      public class myInterface2<T> implements genericInterface<T>{
          public T server(T t) {
              System.out.println(t);
              return null;
          }
      }
      
      public class test {
          public static void main(String[] args) {
              myInterface2<Integer> mi2 = new myInterface2<Integer>();
              mi2.server(20);
          }
      }        
      

泛型方法

  • 调用泛型方法不需要规定类型,其类型由传入的数据决定

    public class genericFunction {
        //泛型方法
        public <T> T show(T t) {//--->T的使用范围仅方法内
            System.out.println("泛型方法" + t);
            return t;
        }
    }
    
    public class test {
        public static void main(String[] args) {
            genericFunction gf = new genericFunction();
            gf.show("String");
        }
    }
    

泛型集合

  • 参数化类型、类型安全的集合,强制集合元素的类型必须一致

  • 特点

    • 编译时即可检查,而非运行时抛出异常
    • 访问时,不必类型转换(拆箱)
    • 不同泛型之间引用不能相互赋值,泛型不存在多态
  • 实例

    import java.util.ArrayList;
    
    public class genericSet {
        public static void main(String[] args) {
            //不规定类型时,默认为Object类,可以存入所有类
            ArrayList arrayList = new ArrayList();
            arrayList.add("xxx");
            arrayList.add("yyy");
            arrayList.add(10);
            arrayList.add(20);
            //使用泛型时,只能存入指定类型的类
            ArrayList<String> strs = new ArrayList<>();
            strs.add("xxx");
            strs.add("yyy");
            //strs.add(10);--->报错
            //strs.add(20);--->报错
        }
    }
    

Set接口与实现类

  • Set子接口特点:无序、无下标、元素不可重复

  • 其方法全部继承自Collection中的方法

  • 实例

    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    
    public class SetTest {
        public static void main(String[] args) {
            //创建集合
            Set<String> set = new HashSet<>();
            //添加数据
            System.out.println("==========add==========");
            set.add("小米");
            set.add("苹果");
            set.add("华为");
            set.add("华为");
            System.out.println("数据个数:" + set.size());
            System.out.println("数据:" + set.toString());
            //删除数据
            System.out.println("==========remove==========");
            set.remove("苹果");
            System.out.println("数据个数:" + set.size());
            System.out.println("数据:" + set.toString());
            //遍历
            System.out.println("==========(1)增强for==========");
            for (String s : set) {
                System.out.println(s.toString());
            }
            System.out.println("==========(2)迭代器:iterator==========");
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
            //判断
            System.out.println("==========contains、isEmpty==========");
            System.out.println("判断“小米”是否在集合中:" + set.contains("小米"));
            System.out.println("判断集合是否为空:" + set.isEmpty());
        }
    }
    

    在这里插入图片描述

HashSet【重点】

  • 存储结构:哈希表

  • 基于HashCode计算元素存放位置

  • 当存入元素的哈希码相同时,会调用equals进行确认,如结果为true,则拒绝后者存入

  • HashSet存储过程

    • 根据hashCode计算保存的位置,如果此位置为空,则直接保存,如果不为空执行第二步
    • 执行equals方法,若结果为true,则认为重复,否则形成链表
  • 实例(String类)

    import java.util.HashSet;
    import java.util.Iterator;
    
    public class HashSetTest {
        public static void main(String[] args) {
            HashSet<String> hashSet = new HashSet<>();
            //添加元素
            System.out.println("==========add==========");
            hashSet.add("xxx");
            hashSet.add("yyy");
            hashSet.add("zzz");
            hashSet.add("www");
            System.out.println("元素个数:" + hashSet.size());
            System.out.println("元素:" + hashSet.toString());
            //删除数据
            System.out.println("==========remove==========");
            hashSet.remove("xxx");
            System.out.println("元素个数:" + hashSet.size());
            System.out.println("元素:" + hashSet.toString());
            //遍历
            System.out.println("==========(1)增强for==========");
            for (String s : hashSet) {
                System.out.println(s);
            }
            System.out.println("==========(2)迭代器:iterator==========");
            Iterator<String> it = hashSet.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
            //判断
            System.out.println("==========contains、isEmpty==========");
            System.out.println("判断“小米”是否在集合中:" + hashSet.contains("小米"));
            System.out.println("判断集合是否为空:" + hashSet.isEmpty());
        }
    }
    

    在这里插入图片描述

  • 实例(Person类)

    public class Person {
        private String name;
        private int age;
        public Person() {
    
        }
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return this.name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return this.age;
        }
        public void setAge() {
            this.age = age;
        }
        public String toString() {
            return "Person [name : "
                    + this.name + "; age : "
                    + this.age + "]";
        }
    }
    
    import java.util.HashSet;
    import java.util.Iterator;
    
    public class HashSetTest2 {
        public static void main(String[] args) {
            //创建集合
            HashSet<Person> person = new HashSet<>();
            //创建Person对象
            Person person1 = new Person("xxx", 18);
            Person person2 = new Person("yyy", 19);
            Person person3 = new Person("zzz", 20);
            Person person4 = new Person("www", 17);
            //添加元素
            System.out.println("==========add==========");
            person.add(person1);
            person.add(person2);
            person.add(person3);
            person.add(person4);
            System.out.println("元素个数:" + person.size());
            System.out.println("元素:" + person.toString());
            //删除数据
            System.out.println("==========remove==========");
            person.remove(person1);
            System.out.println("元素个数:" + person.size());
            System.out.println("元素:" + person.toString());
            //遍历
            System.out.println("==========(1)增强for==========");
            for (Person s : person) {
                System.out.println(s);
            }
            System.out.println("==========(2)迭代器:iterator==========");
            Iterator<Person> it = person.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
            //判断
            System.out.println("==========contains、isEmpty==========");
            System.out.println("判断person1是否在集合中:" + person.contains(person2));
            System.out.println("判断集合是否为空:" + person.isEmpty());
        }
    }
    

    在这里插入图片描述

  • hashset存储原理及重写hsahCode【重点】

TreeSet

  • 基于排列顺序实现元素不重复

  • 实现了SortedSet接口,对集合元素自动排序

  • 元素对象的类型必须实现Comparable接口,指定排序规则

  • 通过Comparable方法确定是否为重复元素

  • 实例

    public class Person implements Comparable<Person>{
        private String name;
        private int age;
        public Person() {
    
        }
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return this.name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return this.age;
        }
        public void setAge() {
            this.age = age;
        }
        public String toString() {
            return "Person [name : "
                    + this.name + "; age : "
                    + this.age + "]";
        }
        public int compareTo(Person o) {
            int n1 = this.getName().compareTo(o.getName());
            int n2 = this.age - o.getAge();
            return n1 == 0?n2:n1;
        }
    }
    
    import java.util.Iterator;
    import java.util.TreeSet;
    
    public class TreeSetTest {
        public static void main(String[] args) {
            TreeSet<Person> treeSet = new TreeSet<>();
            //创建Person对象
            Person person1 = new Person("xxx", 18);
            Person person2 = new Person("yyy", 19);
            Person person3 = new Person("zzz", 20);
            Person person4 = new Person("www", 17);
            //添加元素---->需要比较,即需要实现Comparable接口中的compareTo方法
            treeSet.add(person1);
            treeSet.add(person2);
            treeSet.add(person3);
            treeSet.add(person4);
            System.out.println("元素个数:" + treeSet.size());
            System.out.println("元素:" + treeSet.toString());
            //删除数据
            System.out.println("==========remove==========");
            treeSet.remove(person2);
            System.out.println("元素个数:" + treeSet.size());
            System.out.println("元素:" + treeSet.toString());
            //遍历
            System.out.println("==========(1)增强for==========");
            for (Person s : treeSet) {
                System.out.println(s);
            }
            System.out.println("==========(2)迭代器:iterator==========");
            Iterator<Person> it = treeSet.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
            //判断
            System.out.println("==========contains、isEmpty==========");
            System.out.println("判断“person1”是否在集合中:" + treeSet.contains(person1));
            System.out.println("判断集合是否为空:" + treeSet.isEmpty());
        }
    }
    

    在这里插入图片描述

Map集合体系

  • Map接口特点:
    • 用于存储任意键值对(Key-Value)
    • 键:无序、无下标、不允许重复
    • 值:无序、无下标、允许重复

在这里插入图片描述

Map父接口

  • 特点:存储一对数据,无序,无下标,键不可重复,值可重复

  • 方法:

    • V put(K key, V value):将对象存入到集合中,关联键值。key重复则覆盖原值
    • Object get(Object key):根据键获取对应的值
    • keySet:返回所有key
    • Collection values():返回包含所有值的Collection集合
    • Set<Map.entry<K,V>>:键值匹配的Set集合
  • Map集合的实现类

    • HashMap【重点】
    • Hashtable:JDK1.0版本,线程安全,运行效率慢;不允许null作为Key或Value
    • Properties:Hashtable的子类,要求key和value都是String。通常用于配置文件的读取
    • TreeMap
  • 实例

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class MapTest {
        public static void main(String[] args) {
            //创建Map集合
            Map<String, String> map = new HashMap<>();
            //添加元素
            System.out.println("==========put==========");
            map.put("cn", "中国");
            map.put("uk", "英国");
            map.put("usa", "美国");
            map.put("cn", "zhongguo");
            System.out.println("元素个数:" + map.size());
            System.out.println("元素:" + map.toString());
            //删除元素
            System.out.println("==========remove==========");
            map.remove("usa");
            System.out.println("元素个数:" + map.size());
            System.out.println("元素:" + map.toString());
            //遍历
            System.out.println("==========(1)keySet==========");
            Set<String> s = map.keySet();
            for (String key : s) {
                System.out.println(key + "---------" + map.get(key));
            }
            System.out.println("==========(2)entrySet==========");
            Set<Map.Entry<String, String>> KV = map.entrySet();
            for (Map.Entry<String, String> kv : KV) {
                System.out.println(kv.getKey() + "---------" + kv.getValue());
            }
            //判断
            System.out.println("==========containsKey、containsValue==========");
            System.out.println("判断键“cn”在不在集合中:" + map.containsKey("cn"));
            System.out.println("判断值“美国”在不在集合中:" + map.containsKey("美国"));
        }
    }
    

    在这里插入图片描述

HashMap

  • JDK1.2版本,线程不安全,运行效率快;允许用null作为key或value

  • 初始空集合的默认初始容量为16,默认加载因子为0.75

  • 示例

    import java.util.Objects;
    
    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 void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Student [name : "
                    + this.name + " ; age"
                    + this.age + "]";
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            result = prime * result + age;
            return result;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Student student = (Student) o;
            return age == student.age && Objects.equals(name, student.name);
        }
    }
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class hashMapTest {
        public static void main(String[] args) {
            //创建集合
            HashMap<Student, String> hashMap = new HashMap<>();
            //创建学生对象
            Student s1 = new Student("www", 20);
            Student s2 = new Student("xxx", 21);
            Student s3 = new Student("yyy", 22);
            Student s4 = new Student("zzz", 23);
            //添加元素
            System.out.println("==========put==========");
            hashMap.put(s1, "北京");
            hashMap.put(s2, "上海");
            hashMap.put(s3, "四川");
            hashMap.put(s4, "湖南");
            hashMap.put(s2, "重庆");
            hashMap.put(new Student("xxx", 21), "南京");//--->重写hashCode和equals
            System.out.println("元素个数:" + hashMap.size());
            System.out.println("元素:" + hashMap.toString());
            //删除元素
            System.out.println("==========remove==========");
            hashMap.remove(s1);
            System.out.println("元素个数:" + hashMap.size());
            System.out.println("元素:" + hashMap.toString());
            //遍历
            System.out.println("==========(1)keySet==========");
            Set<Student> keyed = hashMap.keySet();
            for (Student student : keyed) {
                System.out.println(student + ":" + hashMap.get(student));
            }
            System.out.println("==========(2)entrySet===========");
            Set<Map.Entry<Student, String>> KV = hashMap.entrySet();
            for (Map.Entry<Student, String> kv : KV) {
                System.out.println(kv.getKey() + ":" + kv.getValue());
            }
            //判断
            System.out.println("==========containsKey、containsValue");
            System.out.println("判断键s2是否存在:" + hashMap.containsKey(s2));
            System.out.println("判断值\"北京\"是否存在:" + hashMap.containsKey("北京"));
        }
    }
    

    在这里插入图片描述

TreeMap

  • 实现了sortedMap接口(是Map的子接口),可以对key自动排序

  • 示例

    import java.util.Objects;
    
    public class Student implements Comparable<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 void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Student [name : "
                    + this.name + " ; age"
                    + this.age + "]";
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            result = prime * result + age;
            return result;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Student student = (Student) o;
            return age == student.age && Objects.equals(name, student.name);
        }
    
        @Override
        public int compareTo(Student o) {
            int n1 = this.name.compareTo(o.getName());
            int n2 = this.age - o.getAge();
            return (n1 != 0) ? n1 : n2;
        }
    }
    
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeMap;
    
    public class treeMapTest {
        public static void main(String[] args) {
            TreeMap<Student, String> treeMap = new TreeMap<Student, String>();
            //创建学生对象
            Student s1 = new Student("www", 20);
            Student s2 = new Student("xxx", 21);
            Student s3 = new Student("yyy", 22);
            Student s4 = new Student("zzz", 23);
            //添加元素----->必须实现Comparable接口
            System.out.println("==========put==========");
            treeMap.put(s1, "北京");
            treeMap.put(s2, "上海");
            treeMap.put(s3, "四川");
            treeMap.put(s4, "湖南");
            System.out.println("元素个数:" + treeMap.size());
            System.out.println("元素:" + treeMap.toString());
            //删除元素
            System.out.println("==========remove==========");
            treeMap.remove(s2);
            System.out.println("元素个数:" + treeMap.size());
            System.out.println("元素:" + treeMap.toString());
            //遍历
            System.out.println("==========(1)keySet==========");
            Set<Student> keys = treeMap.keySet();
            for (Student key : keys) {
                System.out.println(key + ":" + treeMap.get(key));
            }
            System.out.println("==========(2)entrySet==========");
            Set<Map.Entry<Student, String>> KV = treeMap.entrySet();
            for (Map.Entry<Student, String> kv : KV) {
                System.out.println(kv.getKey() + ":" + kv.getValue());
            }
            //判断
            System.out.println("==========containsKey、containsValue==========");
            System.out.println("判断键“s2”是否在集合中:" + treeMap.containsKey(s2));
            System.out.println("判断值\"上海\"是否在集合中:" + treeMap.containsValue("北京"));
        }
    }
    

    在这里插入图片描述

Collections工具类

  • 集合工具类,定义了除了存取以外的集合常用方法

  • 方法

    • public static void reverse(List<?> list):反转集合中元素的顺序
    • public static void shuffle(List<?> list):随机重置集合元素的顺序
    • public static void sort(List<?> list):升序排序(元素类型必须实现Comparable接口)
  • 示例

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class CollectionsTest {
        public static void main(String[] args) {
            List<Integer> list = new ArrayList<>();
            list.add(10);
            list.add(40);
            list.add(20);
            list.add(60);
            list.add(5);
            //排序
            System.out.println("==========sort==========");
            System.out.println("排序前:" + list.toString());
            Collections.sort(list);
            System.out.println("排序后:" + list.toString());
            //二分查找
            System.out.println("==========binarySearch==========");
            int index = Collections.binarySearch(list, 10);
            System.out.println("元素10的位置:" + index);
            //复制
            System.out.println("==========copy==========");
            List<Integer> list1 = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                list1.add(0);
            }//----->保证list1的大小与list相同
            Collections.copy(list1, list);
            System.out.println("复制后的集合:" + list1.toString());
            //反转
            System.out.println("==========reverse==========");
            Collections.reverse(list);
            System.out.println("反转后:" + list);
            //随机打乱
            System.out.println("==========shuffle==========");
            Collections.shuffle(list);
            System.out.println("打乱后:" + list);
            //list转成数组
            System.out.println("==========list转成数组==========");
            Integer[] arr1 = list.toArray(new Integer[0]);
            Integer[] arr2 = list.toArray(new Integer[10]);
            System.out.println("数组arr1长度:" + arr1.length);
            System.out.println("数组arr2长度:" + arr2.length);
            System.out.println("数组arr1元素:" + Arrays.toString(arr1));
            System.out.println("数组arr2元素:" + Arrays.toString(arr2));
            //数组变成集合
            System.out.println("==========数组变成集合==========");
            String[] names = {"张三", "李四", "王五"};
            List<String> list2 = Arrays.asList(names);//此集合受限,无法添加和删除元素
            System.out.println("转成的集合为:" + list2.toString());
        }
    }
    

    在这里插入图片描述

  • 25
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值