• Java集合---List和Set


    一.List集合

    1. List接口

      java.util.list接口继承自Collection接口,是一种单列集合。

      List集合主要特点是:允许出现重复的元素,元素是有序的,存入和取出的顺序是一样的,是以一种线性方式进行存储的,能够用索引来访问集合中的元素。

    2. List接口常用的方法

      • public void add(int index, E element):在列表中指定的位置上插入指定的元素。
      • public E get(int index):返回此列表中指定位置的元素
      • public E remove(int index):移除此列表中指定位置的元素
      • public E set(int index, E element):用指定元素替换此列表中指定位置的元素
      public class ListDemo1 {
          public static void main(String[] args) {
              List<Integer> list = new ArrayList<>();
      
              list.add(1);
              list.add(3);
              list.add(2);
              // 在指定位置添加add
              list.add(2,4);
              System.out.println(list);   // 输出:[1, 3, 4, 2]
      
              // 删除remove
              list.remove(2);
              System.out.println(list);   // 输出:[1, 3, 2]
      
              // 修改set
              list.set(0,11);
              list.set(2,22);
              System.out.println(list);   // 输出:[11, 3, 22]
      
              // 获取List数据 get
              for (int i = 0; i < list.size(); i++) {
                  System.out.print(list.get(i) + " ");    // 输出:11 3 22 
              }
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
    3. List的子类

      • ArrayList集合

        ArrayList集合存储的结构是数组结构,元素增删慢,查找快,主要多用于查询数据和遍历数据。

      • LinkedList集合

        LinkedList集合存储的结构是链表结构,元素添加,删除快

        LinkedList是一个双向链表,既继承了List的方法,LinkedList提供许多首尾操作的方法,主要有以下一些:

        • public void addFirst(E e):在此列表的开始处插入指定的元素。
        • public void addLast(E e):将指定的元素插入列表的尾部。
        • public E getFirst():返回此列表中的第一个元素。
        • public E getLast():返回此列表中的最后一个元素。
        • public E removeFirst():移除并返回此列表中第一个元素。
        • public E removeLast():移除并返回此列表的最后一个元素。
        • public E pop():从这个列表所表示的堆栈中弹出一个元素。
        • public void push(E e):将一个元素压栈到该列表所表示的堆栈上。
        public class ListDemo2 {
            public static void main(String[] args) {
                LinkedList<String> linkedList = new LinkedList<>();
                // 添加元素
                linkedList.addFirst("张三");
                linkedList.addFirst("李四");
                linkedList.addFirst("王五");
                System.out.println(linkedList); // 输出:[王五, 李四, 张三]
                // 获取元素
                System.out.println(linkedList.getFirst()); // 输出:王五
                System.out.println(linkedList.getLast());  // 输出:张三
                // 删除元素
                System.out.println(linkedList.removeLast()); // 输出:张三
                System.out.println(linkedList); // 输出:[王五, 李四]
        
                System.out.println(linkedList.removeFirst());   // 输出:王五
                System.out.println(linkedList); // 输出:[李四]
        
                // 压栈
                linkedList.push("赵六");
                System.out.println(linkedList); // 输出:[赵六, 李四]
        
                // 出栈
                System.out.println(linkedList.pop()); // 输出:赵六
            }
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16
        • 17
        • 18
        • 19
        • 20
        • 21
        • 22
        • 23
        • 24
        • 25
        • 26

    二.Set集合

    1. Set接口

      java.util.Set接口继承自Collection接口,方法Collection中的基本一致,没有做功能的扩充,只是对于Collection接口来说,Set接口更加严格。

      Set接口的特点:元素无序,没有索引。

      因为Set集合是无序的并且没有索引,所以取出Set集合的元素可以采用迭代器或者增强for

      Set集合子类有多个,这里主要介绍两个:java.util.HashSetjava.util.LinkedHashSet.

    2. Set集合子类

      • HashSet

        HashSet是根据对象的哈希值来确定元素在集合中的存储位置的,因此具有比较良好的存储和查找性能

        HashSet保证元素的唯一性主要依赖于:hashCode和equals方法

        如果集合存储的是自定义对象,要保证元素唯一,就必须重写hashCode和equals方法。

        示例:HashSet存储基本元素

        public class HashSetDemo {
            public static void main(String[] args) {
                HashSet<String> hs = new HashSet<>();
        
                hs.add("张三");
                hs.add("李四");
                hs.add("王五");
                System.out.println(hs); // 输出:[李四, 张三, 王五]
        
                // 遍历元素
                for (String s : hs) {
                    System.out.print(s + " ");
                } // 输出: 李四 张三 王五
            }
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15

        示例:HashSet存储自定义对象

        1.先创建自定义对象(保证元素唯一,需要重写hashCode方法和equals方法)

        import java.util.Objects;
        
        public class Student {
            private String name;
            private int id;
        
            public Student() {
            }
        
            public Student(String name, int id) {
                this.name = name;
                this.id = id;
            }
        
            public String getName() {
                return name;
            }
        
            public int getId() {
                return id;
            }
        
            public void setName(String name) {
                this.name = name;
            }
        
            public void setId(int id) {
                this.id = id;
            }
        
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Student student = (Student) o;
                return id == student.id &&
                        Objects.equals(name, student.name);
            }
        
            @Override
            public int hashCode() {
                return Objects.hash(name, id);
            }
            
            @Override
            public String toString() {
                return "Student{" +
                        "name='" + name + '\'' +
                        ", id=" + id +
                        '}';
            }
        }
        
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16
        • 17
        • 18
        • 19
        • 20
        • 21
        • 22
        • 23
        • 24
        • 25
        • 26
        • 27
        • 28
        • 29
        • 30
        • 31
        • 32
        • 33
        • 34
        • 35
        • 36
        • 37
        • 38
        • 39
        • 40
        • 41
        • 42
        • 43
        • 44
        • 45
        • 46
        • 47
        • 48
        • 49
        • 50
        • 51
        • 52
        • 53

        2.Set集合存储

        public class SetDemo1 {
            public static void main(String[] args) {
                // 1. 创建集合
                HashSet<Student> hs = new HashSet<>();
                // 2. 创建Student对象
                Student st1 = new Student("张三", 1);
                Student st2 = new Student("李四", 2);
                Student st3 = new Student("王五",3);
                Student st4 = new Student("张三",1);
                Student st5 = new Student("李四", 5);
                // 3. 集合添加元素
                hs.add(st1);
                hs.add(st2);
                hs.add(st3);
                hs.add(st4);
                hs.add(st5);
                // 4. 打印输出
                for (Student s: hs) {
                    System.out.println(s);
                }
                // 输出:
                /*
                Student{name='王五', id=3}
                Student{name='张三', id=1}
                Student{name='李四', id=5}
                Student{name='李四', id=2}
                */
            }
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16
        • 17
        • 18
        • 19
        • 20
        • 21
        • 22
        • 23
        • 24
        • 25
        • 26
        • 27
        • 28
        • 29
      • LinkedHashSet

        上面介绍到Set集合是存进去元素是没有顺序的,如果要保证有序,则需要使用LinkedHashSet,它是链表和哈希表组合的一个数据结构。

        public class LinkedHashSetDemo {
            public static void main(String[] args) {
                LinkedHashSet<String> hs = new LinkedHashSet<>();
        
                hs.add("张三");
                hs.add("李四");
                hs.add("王五");
                System.out.println(hs); // 输出:[张三, 李四, 王五]
        
                // 遍历元素
                for (String s : hs) {
                    System.out.print(s + " ");
                } // 输出: 张三 李四 王五
            }
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
  • 相关阅读:
    为什么企业需要一套设备管理系统?
    多线程核心API和Lock锁的使用
    【WCN685X】WCN6856 5G吞吐量测试只有25Mbps问题原因分析及解决方案
    统计学习:逻辑回归与交叉熵损失(Pytorch实现)
    Celery笔记三之task和task的调用
    2024年度“阳江市惠民保”正式发布!阳江市专属补充医疗保险全新升级
    如何拿取 macOS 系统中的图标文件
    MySQL安装教程及CentOS7离线安装步骤详解
    机器人轨迹规划中经常用到的曲线特性小结:Cn连续与Gn连续、Frenet标架、曲率和挠率
    网络建设 之 React数据管理
  • 原文地址:https://blog.csdn.net/chisuisi5702/article/details/126284973