java-集合

本文介绍了Java集合框架的核心接口和实现类,包括Collection、其子接口List和Set的特点与使用方法。详细讲解了ArrayList、LinkedList、HashSet、LinkedHashSet和TreeSet的实现原理和操作,以及Map接口和HashMap的使用,涉及到元素的添加、删除、遍历以及排序机制。此外,还提到了Collections工具类提供的排序、反转和随机排列等操作。
摘要由CSDN通过智能技术生成

java-集合

在这里插入图片描述

一、集合体系结构

  • 集合类的特点

    ​ 提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变

  • 集合类的体系图

    在这里插入图片描述

二、单列集合

2.1 Collection集合(接口)

  • Collection集合概述

    • 是单列集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素

    • JDK 不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

  • Collection集合基本使用

    public class CollectionDemo01 {
        public static void main(String[] args) {
            //创建Collection集合的对象
            Collection<String> c = new ArrayList<String>();
    
            //添加元素:boolean add(E e)
            c.add("hello");
            c.add("world");
            c.add("java");
    
            //输出集合对象
            System.out.println(c);
        }
    }
    
  • Collection集合的常用方法

    方法名说明
    boolean add(E e)添加元素
    boolean remove(Object o)从集合中移除指定的元素
    void clear()清空集合中的元素
    boolean contains(Object o)判断集合中是否存在指定的元素
    boolean isEmpty()判断集合是否为空
    int size()集合的长度,也就是集合中元素的个数
  • Collection集合的遍历

    • 迭代器的介绍
      • 迭代器,集合的专用遍历方式
      • Iterator iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
      • 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
    public class IteratorDemo {
    	public static void main(String[] args) {
        	//创建集合对象
        	Collection<String> c = new ArrayList<>();
    
        	//添加元素
        	c.add("hello");
        	c.add("world");
        	c.add("java");
    
        	//Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
        	Iterator<String> it = c.iterator();
    
        	//用while循环改进元素的判断和获取
        	while (it.hasNext()) {
            	String s = it.next();
            	System.out.println(s);
        	}
    	}
    }
    

2.2 List集合(接口)

  • List集合概述

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

    • 索引
    • 可以存储重复元素
    • 元素存取有序
  • List集合的特有方法

    方法名描述
    void add(int index,E element)在此集合中的指定位置插入指定的元素
    E remove(int index)删除指定索引处的元素,返回被删除的元素
    E set(int index,E element)修改指定索引处的元素,返回被修改的元素
    E get(int index)返回指定索引处的元素
  • ListIterator列表迭代器

    • 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);
    
        	}
       }
    

2.2.1 数据结构

  • 数据结构之栈和队列

    栈结构队列结构
    先进后出先进先出
  • 数据结构之数组和链表

    数组结构链表结构
    查询快、增删慢查询慢、增删快

2.2.2 List集合的实现类(ArrayList, LinkedList)

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

    public class ArrayListDemo {
    	public static void main(String[] args) {
        	//创建ArrayList集合对象
        	ArrayList<Student> array = new ArrayList<Student>();
    
        	//创建学生对象
        	Student s1 = new Student("刘备", 38);
        	Student s2 = new Student("关羽", 35);
    
        	//把学生添加到集合
        	array.add(s1);
        	array.add(s2);
    
        	//普通for:带有索引的遍历方式
        	for(int i=0; i<array.size(); i++) {
            	Student s = array.get(i);
            	System.out.println(s.getName() + "," + s.getAge());
        	}
    	}
    }
    
  • LinkedList集合
    ​ 底层是链表结构实现,查询慢、增删快

  • LinkedList集合的特有功能

    方法名说明
    public void addFirst(E e)在该列表开头插入指定的元素
    public void addLast(E e)将指定的元素追加到此列表的末尾
    public E getFirst()返回此列表中的第一个元素
    public E getLast()返回此列表中的最后一个元素
    public E removeFirst()从此列表中删除并返回第一个元素
    public E removeLast()从此列表中删除并返回最后一个元素

2.3 Set集合(接口)

  • Set集合的特点

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

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

2.3.1 哈希值

  • 哈希值简介

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

  • 如何获取哈希值

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

  • 哈希值的特点

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

2.3.2 HashSet集合(实现类

  • HashSet集合的特点

    • 底层数据结构是哈希表
    • 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致
    • 没有带索引的方法,所以不能使用普通for循环遍历
    • 由于是Set集合,所以是不包含重复元素的集合
  • HashSet集合的基本使用

    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集合特点

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

      • 根据对象的哈希值计算存储位置
        如果当前位置没有元素则直接存入
        如果当前位置有元素存在,则进入第二步

      • 当前元素的元素和已经存在的元素比较哈希值
        如果哈希值不同,则将当前元素进行存储
        如果哈希值相同,则进入第三步

      • 通过equals()方法比较两个元素的内容
        如果内容不相同,则将当前元素进行存储
        如果内容相同,则不存储当前元素

    • HashSet集合保证元素唯一性的图解
      在这里插入图片描述

    • 常见数据结构之哈希表
      在这里插入图片描述

2.3.3 LinkedHashSet集合

  • LinkedHashSet集合特点

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

    public class LinkedHashSetDemo {
        public static void main(String[] args) {
            //创建集合对象
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
    
            //添加元素
            linkedHashSet.add("hello");
            linkedHashSet.add("world");
            linkedHashSet.add("java");
    
            linkedHashSet.add("world");
    
            //遍历集合
            for(String s : linkedHashSet) {
                System.out.println(s);
            }
        }
    }
    

2.3.4 TreeSet集合(实现类

  • TreeSet集合概述

    • 元素有序,可以按照一定的规则进行排序,具体排序方式取决于构造方法
      • TreeSet():根据其元素的自然排序进行排序
      • TreeSet(Comparator comparator) :根据指定的比较器进行排序
    • 没有带索引的方法,所以不能使用普通for循环遍历
    • 由于是Set集合,所以不包含重复元素的集合
  • TreeSet集合基本使用

    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);
            }
        }
    }
    
  • 自然排序Comparable的使用

    • 自然排序,就是让元素所属的类实现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;
          	//按照年龄从小到大排序
         		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());
              }
          }
      }
      
  • 比较器排序Comparator的使用

    • 比较器排序,就是让集合构造方法接收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) {
                      //this.age - s.age
                      //s1,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());
              }
          }
      }
      

三、双列集合

3.1 Map集合(接口)

  • Map集合概述

    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);
        }
    }
    
  • Map集合的基本功能

    方法名说明
    V put(K key,V value)添加元素
    V remove(Object key)根据键删除键值对元素
    void clear()移除所有的键值对元素
    boolean containsKey(Object key)判断集合是否包含指定的键
    boolean containsValue(Object value)判断集合是否包含指定的值
    boolean isEmpty()判断集合是否为空
    int size()集合的长度,也就是集合中键值对的个数
  • Map集合的获取功能

    方法名说明
    V get(Object key)根据键获取值
    Set keySet()获取所有键的集合
    Collection values()获取所有值的集合
    Set<Map.Entry<K,V>> entrySet()获取所有键值对对象的集合
    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);
        	}
    	}
    }
    

四、Collections集合工具类

4.1 Collections概述和使用

  • Collections类的作用

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

  • Collections类常用方法

    方法名说明
    public static void sort(List<T> list)将指定的列表按升序排序
    public static void reverse(List<?> list)反转指定列表中元素的顺序
    public static void shuffle(List<?> 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);
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值