zoukankan      html  css  js  c++  java
  • 10.集合

    1.1集合概述

    集合类的特点:提供一种存储空间可变的存储模型,存储的数据容量可以发生变化,java集合类包含在java.util包下,集合类存放的是对象的引用,而非对象本身,集合类型主要分为Set,List和Map。

    集合类有很多,首先学习ArrayList。

    1.2java集合类图

    1.3Collection集合概述和使用

    • Collection是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素
    • JDK不提供此接口的直接实现,它提供更具体的子接口(如Set和List)实现。
    import java.util.ArrayList;
    import java.util.Collection;
    
    public class myCollection {
        public static void main(String[] args) {
            //创建Collection集合的对象
            //Collection本身是一个接口,无法实例化,故此通过其List子接口的ArrayList实现类来实例化(多态)
            Collection<String> collection = new ArrayList<String>();
            //给collection添加元素
            collection.add("Hello");
            collection.add("World");
            //输出集合对象
            System.out.println(collection);//ArrayList重写了toString()方法
        }
    }

    1.3.1Collection集合常用方法

    1.3.2Collection集合的遍历

    • Iterator:迭代器,集合的专用遍历方式
    • Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator方法得到。
    • 迭代器是通过集合的iterator()方法得到的,所以我们说它依赖于集合而存在。
    //遍历
    Iterator<String> it = collection.iterator();     
    while(it.hasNext()) {
      String s = it.next(); System.
    out.println(s); }

    1.4List集合

    1.4.1List集合概述

    • 有序集合,用户可以精确控制列表每个元素的插入位置,用户可以通过整数索引访问元素,并搜索列表中的元素。
    • 与Set集合不同,列表通常允许重复的元素。

    1.4.2List集合特点

    • 有序:存储和取出的元素顺序一致
    • 可重复:存储的元素可以重复

    1.4.3List集合的特有方法

    1.4.4并发修改异常

    • 出现的原因
      • 迭代器遍历的过程中,通过集合对象修改了集合中的元素,造成了迭代器获取元素中判断预期修改值和实际修改值不一致,则会出现:ConcurrentModificationException
    • 解决的方案
      • 用for循环遍历,然后用集合对象做对应的操作即可
    • 示例代码
    public class ListDemo {
        public static void main(String[] args) {
            //创建集合对象
            List<String> list = new ArrayList<String>();
            //添加元素
            list.add("hello");
            list.add("world");
            list.add("java");
            //遍历集合,得到每一个元素,看有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现
            // Iterator<String> it = list.iterator();
            // while (it.hasNext()) {
                // String s = it.next();
                // if(s.equals("world")) {
                    // list.add("javaee");
                // }
            // }
            for(int i=0; i<list.size(); i++) {
                String s = list.get(i);
                if(s.equals("world")) {
                    list.add("javaee");
                }
            }
            //输出集合对象
            System.out.println(list);
        }
    }

    1.4.5列表迭代器

    • ListIterator介绍
      • 通过List集合的listIterator()方法得到,所以说它是List集合特有的迭代器
      • 用于允许程序员沿任一方向遍历的列表迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置
    public class ListIteratorDemo {
        public static void main(String[] args) {
            //创建集合对象
            List<String> list = new ArrayList<String>();
            //添加元素
            list.add("hello");
            list.add("world");
            list.add("java");
            //获取列表迭代器
            ListIterator<String> lit = list.listIterator();
            while (lit.hasNext()) {
                String s = lit.next();
                if(s.equals("world")) {
                    lit.add("javaee");
                }
            }
            System.out.println(list);
        }
    }

    1.4.6增强for循环

    for(元素数据类型 变量名 : 数组/集合对象名) {
        循环体;
    }
    public class ForDemo {
        public static void main(String[] args) {
            int[] arr = {1,2,3,4,5};
            for(int i : arr) {
                System.out.println(i);
            }
            System.out.println("--------");
            String[] strArray = {"hello","world","java"};
            for(String s : strArray) {
                System.out.println(s);
            }
            System.out.println("--------");
            List<String> list = new ArrayList<String>();
            list.add("hello");
            list.add("world");
            list.add("java");
            for(String s : list) {
                System.out.println(s);
            }
            System.out.println("--------");
            //内部原理是一个Iterator迭代器
            /*
                for(String s : list) {
                    if(s.equals("world")) {
                        list.add("javaee"); //ConcurrentModificationException
                    }
                }
            */
        }
    }

    1.4.7集合的案例-List集合存储学生对象三种方式遍历

    • 学生类
    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;
        }
    }
    • 测试类
    public class ListDemo {
        public static void main(String[] args) {
            //创建List集合对象
            List<Student> list = new ArrayList<Student>();
            //创建学生对象
            Student s1 = new Student("林青霞", 30);
            Student s2 = new Student("张曼玉", 35);
            Student s3 = new Student("王祖贤", 33);
            //把学生添加到集合
            list.add(s1);
            list.add(s2);
            list.add(s3);
            //迭代器:集合特有的遍历方式
            Iterator<Student> it = list.iterator();
            while (it.hasNext()) {
                Student s = it.next();
                System.out.println(s.getName()+","+s.getAge());
            }
            System.out.println("--------");
            //普通for:带有索引的遍历方式
            for(int i=0; i<list.size(); i++) {
                Student s = list.get(i);
                System.out.println(s.getName()+","+s.getAge());
            }
            System.out.println("--------");
            //增强for:最方便的遍历方式
            for(Student s : list) {
                System.out.println(s.getName()+","+s.getAge());
            }
        }
    }

    1.4.8数据结构

    1.4.8.1数据结构之栈和队列
    • 栈结构
      • 先进后出
    • 队列结构
      • 先进先出
    1.4.8.2数据结构之数组和链表
    • 数组结构
      • 查询快、增删慢
    • 链表结构
      • 查询慢、增删快

    1.5List集合的实现类

    1.5.1List集合子类的特点

    • ArrayList集合
      • 底层是数组结构实现,查询快、增删慢
    • LinkedList集合
      • 底层是链表结构实现,查询慢、增删快

    1.5.2ArrayList

    ArrayList是List的子类,允许存放重复的元素,并且是有序的。

    • ArrayList<E>:
      • 可调整大小的数组实现
      • <E>是一种特殊的数据类型--泛型,用于约束集合中存储元素的数据类型
    1.5.2.1ArrayList构造方法和添加方法

    •  示例代码
    import java.util.ArrayList;
    
    public class ArrayListDemo01 {
        public static void main(String[] args) {
            ArrayList<String> array = new ArrayList<String>();
            array.add("hello");
            array.add("world");
            array.add("java");
            array.add(1,"javase");
            //IndexOutOfBoundsException
         //array.add(4,"javaee");
            System.out.println("array:" + array);
    
        }
    }
    1.5.2.2ArrayList集合常用方法

    •  示例代码
    public class ArrayListDemo02 {
        public static void main(String[] args) {
            //创建集合
            ArrayList<String> array = new ArrayList<String>();
            //添加元素
            array.add("hello");
            array.add("world");
            array.add("java");
            //public boolean remove(Object o):删除指定的元素,返回删除是否成功
            // System.out.println(array.remove("world"));
            // System.out.println(array.remove("javaee"));
            //public E remove(int index):删除指定索引处的元素,返回被删除的元素
            // System.out.println(array.remove(1));
            //IndexOutOfBoundsException
            // System.out.println(array.remove(3));
            //public E set(int index,E element):修改指定索引处的元素,返回被修改的元素
            // System.out.println(array.set(1,"javaee"));
            //IndexOutOfBoundsException
            // System.out.println(array.set(3,"javaee"));
            //public E get(int index):返回指定索引处的元素
            // System.out.println(array.get(0));
            // System.out.println(array.get(1));
            // System.out.println(array.get(2));
            //System.out.println(array.get(3)); //?????? 自己测试
            //public int size():返回集合中的元素的个数
            System.out.println(array.size());
            //输出集合
            System.out.println("array:" + array);
        }
    }
    1.5.2.3ArrayList集合存储学生对象三种方式遍历
    public class ArrayListDemo {
        public static void main(String[] args) {
            //创建ArrayList集合对象
            ArrayList<Student> array = new ArrayList<Student>();
            //创建学生对象
            Student s1 = new Student("林青霞", 30);
            Student s2 = new Student("张曼玉", 35);
            Student s3 = new Student("王祖贤", 33);
            //把学生添加到集合
            array.add(s1);
            array.add(s2);
            array.add(s3);
            //迭代器:集合特有的遍历方式
            Iterator<Student> it = array.iterator();
            while (it.hasNext()) {
                Student s = it.next();
                System.out.println(s.getName() + "," + s.getAge());
            }
            System.out.println("--------");
            //普通for:带有索引的遍历方式
            for(int i=0; i<array.size(); i++) {
                Student s = array.get(i);
                System.out.println(s.getName() + "," + s.getAge());
            }
            System.out.println("--------");
            //增强for:最方便的遍历方式
            for(Student s : array) {
                System.out.println(s.getName() + "," + s.getAge());
            }
        }
    }

    说明:ArrayList是一个有序且允许重复和空值的列表。

    1.5.3LinkedList

    LinkedList是一种可以在任何位置进行高效地插入和删除操作的有序序列。

    1.5.3.1LinkedList集合的特有功能

    package com.boxiaoyuan.www;
    
    import java.util.Iterator;
    import java.util.LinkedList;
    
    public class Demo03 {
        public static void main(String[] args) {
            LinkedList<String> linkedList = new LinkedList<String>();
            linkedList.add("张三");
            linkedList.add("李四");
            linkedList.add("王五");
            linkedList.add("赵六");
            linkedList.add("闫七");
            linkedList.add("张三");
            linkedList.add(2, "赵晓鹏");
            linkedList.push("李海");
            linkedList.pop();
            System.out.println("LinkedList输出顺序:");
            Iterator<String> iterator = linkedList.iterator();
            while(iterator.hasNext()) {
                String string = iterator.next();
                System.out.println(string);
            }
        }
    }
    
    ---------输出结果-----------
    LinkedList输出顺序:
    张三
    李四
    赵晓鹏
    王五
    赵六
    闫七
    张三

    说明:LinkedList是有序的双向链表,可以在任意位置进行元素的增加和删除,读取效率低于ArrayList,插入效率高。pop和push方法都是在队头开始的。

    1.5Set集合

    1.5.1Set集合概述

    • Set集合的特点
      • 元素存取无序
      • 没有索引、只能通过迭代器或增强for循环遍历
      • 不能存储重复元素

    1.5.2Set集合的基本使用

    public class SetDemo {
        public static void main(String[] args) {
            //创建集合对象
            Set<String> set = new HashSet<String>();
            //添加元素
            set.add("hello");
            set.add("world");
            set.add("java");
            //不包含重复元素的集合
            set.add("world");
            //遍历
            for(String s : set) {
                System.out.println(s);
            }
        }
    }

    1.5.3哈希值

    1.5.3.1哈希值简介

    是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值

    1.5.3.2如何获取哈希值

    Object类中的public int hashCode():返回对象的哈希码值

    1.5.3.3哈希值的特点

    同一个对象多次调用hashCode()方法返回的哈希值是相同的,默认情况下,不同对象的哈希值是不同的。而重写hashCode()方法,可以实现让不同对象的哈希值相同。

    public class HashDemo {
        public static void main(String[] args) {
            //创建学生对象
            Student s1 = new Student("林青霞",30);
            //同一个对象多次调用hashCode()方法返回的哈希值是相同的
            System.out.println(s1.hashCode()); //1060830840
            System.out.println(s1.hashCode()); //1060830840
            System.out.println("--------");
            Student s2 = new Student("林青霞",30);
            //默认情况下,不同对象的哈希值是不相同的
            //通过方法重写,可以实现不同对象的哈希值是相同的
            System.out.println(s2.hashCode()); //2137211482
            System.out.println("--------");
            System.out.println("hello".hashCode()); //99162322
            System.out.println("world".hashCode()); //113318802
            System.out.println("java".hashCode()); //3254818
            System.out.println("world".hashCode()); //113318802
            System.out.println("--------");
            System.out.println("重地".hashCode()); //1179395
            System.out.println("通话".hashCode()); //1179395
        }
    }

    1.5.4HashSet

    HashSet是Set接口的子类,主要特点是:

    • 底层数据结构是哈希表
    • 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致
    • 没有带索引的方法,所以不能使用普通for循环遍历
    • 由于是Set集合,所以是不包含重复元素的集合
    public class HashSetDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            HashSet<String> hs = new HashSet<String>();
            //添加元素
            hs.add("hello");
            hs.add("world");
            hs.add("java");
            hs.add("world");
            //遍历
            for(String s : hs) {
                System.out.println(s);
            }
        }
    }

    说明:HashSet存放的值是无序且不能重复的,可以存放null,但是只能存放一个null值。HashSet继承AbstractSet,有两个很重要的方法:HashCode和equals,当对象被存储到HashSet中时,会调用HashCode,获取对象的存放位置。

    1.5.4.1HashSet集合保证元素唯一性的原理

    1.根据对象的哈希值计算存储位置

    • 如果当前位置没有元素则直接存入
    • 如果当前位置有元素存在,则进入第二步

    2.遍历当前位置的所有元素和新存入的元素比较哈希值

    • 如果哈希值不同,则将当前元素进行存储
    • 如果哈希值相同,则进入第三步

    3.通过equals()方法比较两个元素的内容

    • 如果内容不相同,则将当前元素进行存储
    • 如果内容相同,则不存储当前元素
    1.5.4.2HashSet集合存储学生对象并遍历
    • 学生类
    import java.util.Objects;
    
    public class Student {
        private String name;
        private String age;
        //Alt+Insert自动生成
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public String getAge() {
            return age;
        }
    
        public Student(String name, String age) {
            this.name = name;
            this.age = age;
        }
        
        //Alt+Insert自动生成
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Student student = (Student) o;
            return Objects.equals(name, student.name) &&
                    Objects.equals(age, student.age);
        }
    
        @Override
        public int hashCode() {
            return Objects.hash(name, age);
        }
    }
    • 测试类
    public class HashSetDemo {
        public static void main(String[] args) {
            HashSet<Student> hs = new HashSet<Student>();
    
            Student s1 = new Student("张三", "18");
            Student s2 = new Student("李四", "22");
            Student s3 = new Student("李四", "22");
            hs.add(s1);
            hs.add(s2);
            hs.add(s3);
            for(Student s : hs){
                System.out.println(s.getName()+"---"+s.getAge());
            }
        }
    }

    1.5.5LinkedHashSet

    1.5.5.1LinkedHashSet集合特点

      哈希表和链表实现的Set接口,具有可预测的迭代次序,由链表保证元素有序,也就是说元素的存储和取出顺序是一致的,由哈希表保证元素唯一,也就是说没有重复的元素

      LinkedHashSet是HashSet的一个子类,LinkedHashSet的底层用的是LinkedHashMap,HashSet的底层用的是HashMap。

    1.5.5.2LinkedHashSet集合基本使用
    package com.boxiaoyuan.www;
    
    import java.util.Iterator;
    import java.util.LinkedHashSet;
    
    public class Demo03 {
        public static void main(String[] args) {
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
            linkedHashSet.add("张三");
            linkedHashSet.add("李四");
            linkedHashSet.add("王五");
            linkedHashSet.add("赵六");
            linkedHashSet.add("闫七");
            linkedHashSet.add("张三");
            System.out.println("LinkedHashSet输出顺序:");
            Iterator<String> iterator = linkedHashSet.iterator();
            while(iterator.hasNext()) {
                String string = iterator.next();
                System.out.println(string);
            }
        }
    }
    
    ---------输出结果---------
    LinkedHashSet输出顺序:
    张三
    李四
    王五
    赵六
    闫七

    说明:LinkedHashSet中存放的元素是有序,不能重复的。

    1.5.6TreeSet

    1.5.6.1TreeSet集合概述

    元素有序,可以按照一定的规则进行排序,具体排序方式取决于构造方法

    • TreeSet():根据其元素的自然排序进行排序
    • TreeSet(Comparator comparator) :根据指定的比较器进行排序

    没有带索引的方法,所以不能使用普通for循环遍历

    由于是Set集合,所以不包含重复元素的集合

    1.5.6.2TreeSet集合基本使用
    public class TreeSetDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            TreeSet<Integer> ts = new TreeSet<Integer>();
            //添加元素
            ts.add(10);
            ts.add(40);
            ts.add(30);
            ts.add(50);
            ts.add(20);
            ts.add(30);
            //遍历集合
            for(Integer i : ts) {
                System.out.println(i);
            }
        }
    }
    1.5.6.3自然排序Comparable的使用

    案例需求

    • 存储学生对象并遍历,创建TreeSet集合使用无参构造方法
    • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

    实现步骤

    • 用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对元素进行排序的
    • 自然排序,就是让元素所属的类实现Comparable接口,重写compareTo(T o)方法
    • 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写

    代码实现

    • 学生类
    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 int compareTo(Student s) {
            // return 0;
            // return 1;
            // return -1;
            //按照年龄从小到大排序,this代表新增加的元素
            int num = this.age - s.age;
            // int num = s.age - this.age;
            //年龄相同时,按照姓名的字母顺序排序
            int num2 = num==0?this.name.compareTo(s.name):num;
            return num2;
        }
    }
    • 测试类
    public class TreeSetDemo02 {
        public static void main(String[] args) {
            //创建集合对象
            TreeSet<Student> ts = new TreeSet<Student>();
            //创建学生对象
            Student s1 = new Student("xishi", 29);
            Student s2 = new Student("wangzhaojun", 28);
            Student s3 = new Student("diaochan", 30);
            Student s4 = new Student("yangyuhuan", 33);
            Student s5 = new Student("linqingxia",33);
            Student s6 = new Student("linqingxia",33);
            //把学生添加到集合
            ts.add(s1);
            ts.add(s2);
            ts.add(s3);
            ts.add(s4);
            ts.add(s5);
            ts.add(s6);
            //遍历集合
            for (Student s : ts) {
                System.out.println(s.getName() + "," + s.getAge());
            }
        }
    }
    • 如果将compareTo()返回值写死为0,元素值每次比较,都认为是相同的元素,这时就不再向TreeSet中插入除第一个外的新元素。所以TreeSet中就只存在插入的第一个元素。
    • 如果将compareTo()返回值写死为1,元素值每次比较,都认为新插入的元素比上一个元素大,于是二叉树存储时,会存在根的右侧,读取时就是正序排列的。
    • 如果将compareTo()返回值写死为-1,元素值每次比较,都认为新插入的元素比上一个元素小,于是二叉树存储时,会存在根的左侧,读取时就是倒序序排列的。
    1.5.6.4比较器排序Comparator的使用

    案例需求

    • 存储学生对象并遍历,创建TreeSet集合使用带参构造方法
    • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

    实现步骤

    • 用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序的
    • 比较器排序,就是让集合构造方法接收Comparator的实现类对象,重写compare(T o1,T o2)方法
    • 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写

    代码实现

    • 学生类
    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;
        }
    }
    • 测试类
    public class TreeSetDemo {
        public static void main(String[] args) {
            //创建集合对象
            TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>
                    () {
                            @Override
                            public int compare(Student s1, Student s2) {
                            int num = s1.getAge() - s2.getAge();
                            int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                            return num2;
                        }
            });
            //创建学生对象
            Student s1 = new Student("xishi", 29);
            Student s2 = new Student("wangzhaojun", 28);
            Student s3 = new Student("diaochan", 30);
            Student s4 = new Student("yangyuhuan", 33);
            Student s5 = new Student("linqingxia",33);
            Student s6 = new Student("linqingxia",33);
            //把学生添加到集合
            ts.add(s1);
            ts.add(s2);
            ts.add(s3);
            ts.add(s4);
            ts.add(s5);
            ts.add(s6);
            //遍历集合
            for (Student s : ts) {
                System.out.println(s.getName() + "," + s.getAge());
            }
        }
    }

    1.6泛型

    1.6.1泛型概述和好处

    是JDK5中引入的特性,它提供了编译时类型安全检测机制,该机制允许在编译时检测到非法的类型,它的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。一提到参数,最熟悉的就是定义方法时有形参,然后调用此方法时传递实参。那么参数化类型怎么理解呢?顾名思义,就是将类型由原来的具体的类型参数化,然后在使用/调用时传入具体的类型。这种参数类型可以用在类、方法和接口中,分别被称为泛型类、泛型方法、泛型接口。

    • 泛型定义格式
      • <类型>:指定一种类型的格式。这里的类型可以看成是形参
      • <类型1,类型2…>:指定多种类型的格式,多种类型之间用逗号隔开。这里的类型可以看成是形参
      • 将来具体调用时候给定的类型可以看成是实参,并且实参的类型只能是引用数据类型
    • 泛型的好处
      • 把运行时期的问题提前到了编译期间
      • 避免了强制类型转换

    1.6.2泛型类

    • 定义格式
    修饰符 class 类名<类型> { }

    示例代码

    public class Generic<T> {
        private T t;
        public T getT() {
            return t;
        }
        public void setT(T t) {
            this.t = t;
        }
    }
    • 测试类
    public class GenericDemo {
        public static void main(String[] args) {
            Generic<String> g1 = new Generic<String>();
            g1.setT("林青霞");
            System.out.println(g1.getT());
            Generic<Integer> g2 = new Generic<Integer>();
            g2.setT(30);
            System.out.println(g2.getT());
            Generic<Boolean> g3 = new Generic<Boolean>();
            g3.setT(true);
            System.out.println(g3.getT());
        }
    }

    1.6.3泛型方法

    • 定义格式
    修饰符 <类型> 返回值类型 方法名(类型 变量名) { }
    • 示例代码
    public class Generic {
        public <T> void show(T t) {
            System.out.println(t);
        }
    }
    • 测试代码
    public class GenericDemo {
        public static void main(String[] args) {
            Generic g = new Generic();
            g.show("林青霞");
            g.show(30);
            g.show(true);
            g.show(12.34);
        }
    }

    1.6.4泛型接口

    • 定义格式
    修饰符 interface 1 接口名<类型> { }
    • 示例代码
    public interface Generic<T> {
        void show(T t);
    }
    
    public class GenericImpl<T> implements Generic<T> {
        @Override
        public void show(T t) {
            System.out.println(t);
        }
    }
    • 测试代码
    public class GenericDemo {
        public static void main(String[] args) {
            Generic<String> g1 = new GenericImpl<String>();
            g1.show("林青霞");
            Generic<Integer> g2 = new GenericImpl<Integer>();
            g2.show(30);
        }
    }

    1.6.5类型通配符

    • 类型通配符的作用

        为了表示各种泛型List的父类,可以使用类型通配符

    • 类型通配符的分类
      • 类型通配符:<?>
        • List<?>:表示元素类型未知的List,它的元素可以匹配任何的类型
        • 这种带通配符的List仅表示它是各种泛型List的父类,并不能把元素添加到其中
      • 类型通配符上限:<? extends 类型>
        • List<? extends Number>:它表示的类型是Number或者其子类型
      • 类型通配符下限:<? super 类型>
        • List<? super Number>:它表示的类型是Number或者其父类型
    • 示例
    public class GenericDemo {
        public static void main(String[] args) {
            //类型通配符:<?>
            List<?> list1 = new ArrayList<Object>();
            List<?> list2 = new ArrayList<Number>();
            List<?> list3 = new ArrayList<Integer>();
            System.out.println("--------");
            //类型通配符上限:<? extends 类型>
            // List<? extends Number> list4 = new ArrayList<Object>();
            List<? extends Number> list5 = new ArrayList<Number>();
            List<? extends Number> list6 = new ArrayList<Integer>();
            System.out.println("--------");
            //类型通配符下限:<? super 类型>
            List<? super Number> list7 = new ArrayList<Object>();
            List<? super Number> list8 = new ArrayList<Number>();
            // List<? super Number> list9 = new ArrayList<Integer>();
        }
    }

    1.7可变参数

    • 可变参数介绍

        可变参数又称参数个数可变,用作方法的形参出现,那么方法参数个数就是可变的了

    • 可变参数定义格式
    修饰符 返回值类型   方法名(数据类型… 变量名) { }
    • 可变参数的注意事项
      • 这里的变量其实是一个数组
      • 如果一个方法有多个参数,包含可变参数,可变参数要放在最后
    • 可变参数的基本使用
    public class ArgsDemo01 {
        public static void main(String[] args) {
            System.out.println(sum(10, 20));
            System.out.println(sum(10, 20, 30));
            System.out.println(sum(10, 20, 30, 40));
            System.out.println(sum(10,20,30,40,50));
            System.out.println(sum(10,20,30,40,50,60));
            System.out.println(sum(10,20,30,40,50,60,70));
            System.out.println(sum(10,20,30,40,50,60,70,80,90,100));
        }
        // public static int sum(int b,int... a) {
            // return 0;
        // }
        public static int sum(int... a) {
            int sum = 0;
            for(int i : a) {
                sum += i;
            }
            return sum;
        }
    }

    1.8Map集合

    1.8.1Map集合概述和特点

    interface Map<K,V> K:键的类型;V:值的类型
    • Map集合的特点
      • 键值对映射关系
      • 一个键对应一个值
      • 键不能重复,值可以重复
      • 元素存取无序
    • Map集合的基本使用
    public class MapDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String,String> map = new HashMap<String,String>();
            //V put(K key, V value) 将指定的值与该映射中的指定键相关联
            map.put("001","林青霞");
            map.put("002","张曼玉");
            map.put("003","王祖贤");
            map.put("003","柳岩");
            //输出集合对象
            System.out.println(map);
        }
    }

    1.8.2Map集合的基本功能

    • 示例代码
    public class MapDemo02 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String,String> map = new HashMap<String,String>();
            //V put(K key,V value):添加元素
            map.put("张无忌","赵敏");
            map.put("郭靖","黄蓉");
            map.put("杨过","小龙女");
            //V remove(Object key):根据键删除键值对元素
            // System.out.println(map.remove("郭靖"));
            // System.out.println(map.remove("郭襄"));
            //void clear():移除所有的键值对元素
            // map.clear();
            //boolean containsKey(Object key):判断集合是否包含指定的键
            // System.out.println(map.containsKey("郭靖"));
            // System.out.println(map.containsKey("郭襄"));
            //boolean isEmpty():判断集合是否为空
            // System.out.println(map.isEmpty());
            //int size():集合的长度,也就是集合中键值对的个数
            System.out.println(map.size());
            //输出集合对象
            System.out.println(map);
        }
    }

    1.8.3Map集合的获取功能

    •  示例代码
    public class MapDemo03 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
            //V get(Object key):根据键获取值
            // System.out.println(map.get("张无忌"));
            // System.out.println(map.get("张三丰"));
            //Set<K> keySet():获取所有键的集合
            // Set<String> keySet = map.keySet();
            // for(String key : keySet) {
                // System.out.println(key);
            // }
            //Collection<V> values():获取所有值的集合
            Collection<String> values = map.values();
            for(String value : values) {
                System.out.println(value);
            }
        }
    }

    1.8.4Map集合的遍历(方式1)

    public class MapDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
            //获取所有键的集合。用keySet()方法实现
            Set<String> keySet = map.keySet();
            //遍历键的集合,获取到每一个键。用增强for实现
            for (String key : keySet) {
            //根据键去找值。用get(Object key)方法实现
                String value = map.get(key);
                System.out.println(key + "," + value);
            }
        }
    }

    1.8.5Map集合的遍历(方式2)

    public class MapDemo02 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
            //获取所有键值对对象的集合
            Set<Map.Entry<String, String>> entrySet = map.entrySet();
            //遍历键值对对象的集合,得到每一个键值对对象
            for (Map.Entry<String, String> me : entrySet) {
                //根据键值对对象获取键和值
                String key = me.getKey();
                String value = me.getValue();
                System.out.println(key + "," + value);
            }
        }
    }

    1.8.6HashMap

    • HashMap的存储原理:
      • 往HashMap中存储元素的时候,首先HashMap会调用hashCode方法得到一个哈希码值,然后通过这个哈希码值可以计算出该元素的位置。
      • 情况一:如果根据键的哈希码值算出的位置目前没有任何元素存储,那么该元素可以直接加到哈希表中。
      • 情况二:如果根据键的哈希码值算出的位置目前已经有其他元素存储了,那么还会调用键的equals方法与这个位置的元素比较一次,如果equals返回的是true,那么该元素被视为重复元素,不允许添加,如果equals方法返回的是false,该元素可以被添加。
    package com.boxiaoyuan.www;
    
    public class Person {
        private String name;
        private int age;
        
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public String toString() {
            return "name:"+this.name+"  age:"+this.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 int hashCode() {
            return this.name.hashCode()+this.age*25;
        }
        
        @Override
        public boolean equals(Object obj) {
            if(obj instanceof Person) {
                Person person = (Person)obj;
                return this.name.equals(person.name)&&this.age==person.age;
            }else {
                return false;
            }
        }
    }
    package com.boxiaoyuan.www;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map.Entry;
    import java.util.Set;
    
    public class Demo04 {
        public static void main(String[] args) {
            HashMap<Person, String> hMap = new HashMap<Person, String>();
            hMap.put(new Person("张三", 12), "100001");
            hMap.put(new Person("李四", 11), "100002");
            hMap.put(new Person("王五", 14), "100003");
            hMap.put(new Person("赵六", 17), "100004");
            hMap.put(new Person("闫琪", 22), "100005");
            System.out.println(hMap.put(new Person("闫琪", 22), "200005"));
            Set<Entry<Person, String>> set = hMap.entrySet();
            Iterator<Entry<Person, String>> iterator=set.iterator();
            while(iterator.hasNext()) {
                Entry<Person, String> entry = iterator.next();
                System.out.println(entry.getKey()+"====="+entry.getValue());
            }
        }
    }
    
    --------输出结果--------
    100005
    name:赵六  age:17=====100004
    name:闫琪  age:22=====200005
    name:王五  age:14=====100003
    name:李四  age:11=====100002
    name:张三  age:12=====100001

    1.8.7TreeMap

    • TreeMap可以对集合中的键进行排序,有两种方式:
      • 方式一:元素自身具有比较性,和TreeSet原理一样,需要让存在键位置的对象实现Comparable接口,重写compareTo方法。
      • 方式二:容器具备比较性,定义一个类实现接口Comparator,重写compare方法,并将该接口的子类实例对象作为参数传递给TreeMap集合的构造方法。
      • 当Comparable比较方式和Comparator比较方式同时存在时,以Comparator的比较方式为主。
    package com.boxiaoyuan.www;
    
    import java.util.Iterator;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.TreeMap;
    
    public class Demo04 {
        public static void main(String[] args) {
            TreeMap<Person, String> tMap = new TreeMap<Person, String>();
            tMap.put(new Person("张三", 12), "100001");
            tMap.put(new Person("李四", 11), "100002");
            tMap.put(new Person("王五", 14), "100003");
            tMap.put(new Person("赵六", 17), "100004");
            tMap.put(new Person("闫琪", 22), "100005");
            System.out.println(tMap.put(new Person("闫琪", 22), "200005"));
            Set<Entry<Person, String>> set = tMap.entrySet();
            Iterator<Entry<Person, String>> iterator=set.iterator();
            while(iterator.hasNext()) {
                Entry<Person, String> entry = iterator.next();
                System.out.println(entry.getKey()+"====="+entry.getValue());
            }
        }
    }
    
    ---------输出结果--------
    100005
    name:闫琪  age:22=====200005
    name:赵六  age:17=====100004
    name:王五  age:14=====100003
    name:张三  age:12=====100001
    name:李四  age:11=====100002

    说明:Set元素重复元素不能存入,add方法返回false;Map的重复键将覆盖旧键,将旧值返回。

    1.9Collections集合工具类

    1.9.1Collections集合工具类

    Collections类是针对集合操作的工具类

    1.9.2Collections类常用方法

    • 示例代码
    package com.inspur.demo01;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class CollectionsDemo01{
        public static void main(String[] args) {
            //创建集合对象
            List<Integer> list = new ArrayList<Integer>();
            //添加元素
            list.add(30);
            list.add(20);
            list.add(50);
            list.add(10);
            list.add(40);
            //public static <T extends Comparable<? super T>> void sort(List<T> list):将指定的列表按升序排序
            //Collections.sort(list);
            //public static void reverse(List<?> list):反转指定列表中元素的顺序
            //Collections.reverse(list);
            //public static void shuffle(List<?> list):使用默认的随机源随机排列指定的列表
            Collections.shuffle(list);
            System.out.println(list);
        }
    }

    1.9.3ArrayList集合存储学生并排序

    • 学生类
    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;
        }
    }
    • 测试类
    public class CollectionsDemo02 {
        public static void main(String[] args) {
            //创建ArrayList集合对象
            ArrayList<Student> array = new ArrayList<Student>();
            //创建学生对象
            Student s1 = new Student("linqingxia", 30);
            Student s2 = new Student("zhangmanyu", 35);
            Student s3 = new Student("wangzuxian", 33);
            Student s4 = new Student("liuyan", 33);
            //把学生添加到集合
            array.add(s1);
            array.add(s2);
            array.add(s3);
            array.add(s4);
            //使用Collections对ArrayList集合排序
            //sort•(List<T> list, Comparator<? super T> c)
            Collections.sort(array, new Comparator<Student>() {
                @Override
                public int compare(Student s1, Student s2) {
                    //按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
                    int num = s1.getAge() - s2.getAge();
                    int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                    return num2;
                }
            });
            //遍历集合
            for (Student s : array) {
                System.out.println(s.getName() + "," + s.getAge());
            }
        }
    }
  • 相关阅读:
    122. 买卖股票的最佳时机 II-leetcode
    SQL优化
    《C++ Primer Plus》读书笔记之十二—C++中的代码重用
    《C++ Primer Plus》读书笔记之十一—类继承
    《C++ Primer Plus》读书笔记之十—类和动态内存分配
    《C++ Primer Plus》读书笔记之九—使用类
    《C++ Primer Plus》读书笔记之八—对象和类
    一道算法题-换钱
    《C++ Primer Plus》读书笔记之七—内存模型和名称空间
    《C++ Primer Plus》读书笔记之六—函数探幽
  • 原文地址:https://www.cnblogs.com/zhuzhaoli/p/10810024.html
Copyright © 2011-2022 走看看