数据结构-集合框架-java版(完整+简洁+直击要害)

今天刷算法题需要用集合来解,找了几篇博客都没有我想要的效果,不是内容不全,就是篇幅太长,索性我自己写了一篇文章来把集合讲清楚,废话不多说,直接看图,理清集合的族谱

  • 1.Collection集合概述
    • 是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素
    • 创建对象: Collection<String> c = new ArrayList<>();
    • Collection集合常用方法
      • 方法名

        说明

        boolean add(E e)

        添加元素

        boolean remove(Object o)

        从集合中移除指定的元素

        boolean removeIf(Object o)

        根据条件进行移除

        void clear()

        清空集合中的元素

        boolean contains(Object o)

        判断集合中是否存在指定的元素

        boolean isEmpty()

        判断集合是否为空

        int size()

        集合的长度,也就是集合中元素的个数

    • 迭代器介绍
      • 迭代器,集合的专用遍历方式
      • Iterator<E> iterator(): 返回此集合中元素的迭代器,通过集合对象的iterator()方法得到
    • Iterator中的常用方法

          boolean hasNext(): 判断当前位置是否有元素可以被取出

          E next(): 获取当前位置的元素,将迭代器对象移向下一个索引位置

对上述知识点举个例子:

public class IteratorDemo1 {
    
public static void main(String[] args) {
        
//创建集合对象
        Collection<String> c = new ArrayList<>();

        
//添加元素
        c.add("hello");
        c.add(
"world");
        c.add(
"java");
        c.add(
"javaee");

        
//Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
        Iterator<String> it = c.iterator();

        
//while循环改进元素的判断和获取
        while (it.hasNext()) {
            
String s = it.next();
            System.out.println(s);
        }
    }
}

2.List集合list作为Collection的子接口,Conllction中的方法List都可以使用

  • List集合的特点
    • 存取有序
    • 可以重复
    • 有索引 

List集合的特有方法【应用】 

方法名

描述

void add(int index,E element)

在此集合中的指定位置插入指定的元素

E remove(int index)

删除指定索引处的元素,返回被删除的元素

E set(int index,E element)

修改指定索引处的元素,返回被修改的元素

E get(int index)

返回指定索引处的元素

 举个例子:

        public class MyListDemo {
    
public static void main(String[] args) {
        List<
String> list = new ArrayList<>();
        list.add(
"aaa");
        list.add(
"bbb");
        list.add(
"ccc");
        
//method1(list);
        //method2(list);
        //method3(list);
        //method4(list);
    }

    
private static void method4(List<String> list) {
        
//        E get(int index)      返回指定索引处的元素
        String s = list.get(0);
        System.out.println(s);
    }

    
private static void method3(List<String> list) {
        
//        E set(int index,E element)    修改指定索引处的元素,返回被修改的元素
 

        //被替换的那个元素,在集合中就不存在了.
        String result = list.set(0, "qqq");
        System.out.println(result);
        System.out.println(list);
    }

其他没有举例子子的方法,基本用法都是一样的 

3.LinkedList集合(底层是链表结构实现,查询慢、增删快)(Collection和list的方法都可以使用)

LinkedList集合的特有功能【应用】

  • 特有方法
  • 方法名

    说明

    public void addFirst(E e)

    在该列表开头插入指定的元素

    public void addLast(E e)

    将指定的元素追加到此列表的末尾

    public E getFirst()

    返回此列表中的第一个元素

    public E getLast()

    返回此列表中的最后一个元素

    public E removeFirst()

    从此列表中删除并返回第一个元素

    public E removeLast()

    从此列表中删除并返回最后一个元素

 4.ArrayList(底层是数组)——通常使用Collection的方法 

5.Set集合 (Set是Collection的子接口,可以使用Colection提供的所有方法)

  • Set集合的特点
    • 存取有序
    • 不可以重复
    • 无索引 (不可以使用普通的for循环遍历)

 Set集合的使用【应用】

使用Collection的方法——迭代器的遍历and增强for进行遍历

public class MySet1 {
    
public static void main(String[] args) {
     
  //创建集合对象
        Set<String> set = new TreeSet<>();
     
  //添加元素
        set.add("ccc");
        set.add(
"aaa");
        set.add(
"aaa");
        set.add(
"bbb");

//        for (int i = 0; i < set.size(); i++) {
//            //Set集合是没有索引的,所以不能使用通过索引获取元素的方法
//        }
      
     
  //遍历集合
        Iterator<String> it = set.iterator();
        
while (it.hasNext()){

            String s = it.next();
            System.out.println(s);
        }
        System.out.println(
"-----------------------------------");
        
for (String s : set) {
            System.out.println(s);
        }
    }
}

6.TreeSet集合

TreeSet集合特点

        和Set方法一样

7.HashSet集合

HashSet集合概述和特点【应用】

  • 底层数据结构是哈希表
  • 其他特性同Set一样
  • public class HashSetDemo {
        
    public static void main(String[] args) {
            
    //创建集合对象
            HashSet<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);
            }
        }
  • }
  • 哈希值【理解】

  • 哈希值简介
  •   JDK根据对象的地址或者字符串或者数字算出来的int类型的数值

  • 如何获取哈希值
  •   Object类中的public int hashCode():返回对象的哈希码值

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

哈希表结构【理解】

  • JDK1.8以前

  数组 + 链表

  • JDK1.8以后
    • 节点个数少于等于8个

   数组 + 链表

    • 节点个数多于8个

   数组 + 红黑树

HashSet集合存储学生对象并遍历【应用】

  • 案例需求
    • 创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合
    • 要求:学生对象的成员变量值相同,我们就认为是同一个对象
  • 代码实现

学生类

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 boolean equals(Object o) {
        
if (this == o) return true;
        
if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        
if (age != student.age) return false;
        
return name != null ? name.equals(student.name) : student.name == null;
    }

    
@Override
    public int hashCode() {
        
int result = name != null ? name.hashCode() : 0;
        result =
31 * result + age;
        
return result;
    }

}

测试类

public class HashSetDemo02 {
    
public static void main(String[] args) {
        
//创建HashSet集合对象
        HashSet<Student> hs = new HashSet<Student>();

        
//创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 =
new Student("张曼玉", 35);
        Student s3 =
new Student("王祖贤", 33);

        Student s4 =
new Student("王祖贤", 33);

        
//把学生添加到集合
        hs.add(s1);
        hs.add(s2);

        hs.add(s3);
        hs.add(s4);

        
//遍历集合(增强for)
        for (Student s : hs) {
            System.out.println(s.getName() +
"," + s.getAge());
        }
    }

}

  • 总结

  HashSet集合存储自定义类型元素,要想实现元素的唯一,要求必须重写hashCode方法和equals方法

8.Map集合

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("itheima001","林青霞");
        map.put(
"itheima002","张曼玉");
        map.put(
"itheima003","王祖贤");
        map.put(
"itheima003","柳岩");

        
//输出集合对象
        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()

集合的长度,也就是集合中键值对的个数

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


}

Map集合的获取功能【应用】

方法名

说明

V get(Object key)

V getOrDefault(Object key,默认值)

根据键获取值

根据键获取值,如果key不存在,返回默认值

Set<K> keySet()

获取所有键的集合

Collection<V> 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);
        }
    }

}

遍历方式一:

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

}

遍历方式二:

        ...上面部分不变

 //获取所有键值对对象的集合
        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);
        }

9.HashMap集合

  • HashMap底层是哈希表结构的
  • 依赖hashCode方法和equals方法保证键的唯一
  • 如果键要存储的是自定义对象,需要重写hashCode和equals方法

public class Student {
    
private String name;
    
private int age;

    
public Student() {
    }

    
public Student(String name, int age) {
        
this.name = name;
        
this.age = age;
    }

省略get、set方法

@Override
    public boolean equals(Object o) {
        
if (this == o) return true;
        
if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        
if (age != student.age) return false;
        
return name != null ? name.equals(student.name) : student.name == null;
    }


@Override
    public int hashCode(){       

         int result = name != null ? name.hashCode() : 0;
        result =
31 * result + age;
        
return result;
    }

}

10.TreeMap集合 

TreeMap底层是红黑树结构

+ 依赖自然排序或者比较器排序,对键进行排序

+ 如果键存储的是自定义对象,需要实现Comparable接口或者在创建TreeMap对象时候给出比较器排序规则

实例:封装Student对象之后,在方法中重写

   @Override

      public int compareTo(Student o) {

          //按照年龄进行排序

          int result = o.getAge() - this.getAge();

          //次要条件,按照姓名排序。

          result = result == 0 ? o.getName().compareTo(this.getName()) : result;

          return result;

      }

测试:

 public class Test1 {

      public static void main(String[] args) {

            // 创建TreeMap集合对象

          TreeMap<Student,String> tm = new TreeMap<>();

        // 创建学生对象

          Student s1 = new Student("xiaohei",23);

          Student s2 = new Student("dapang",22);

          Student s3 = new Student("xiaomei",22);

        // 将学生对象添加到TreeMap集合中

          tm.put(s1,"江苏");

          tm.put(s2,"北京");

          tm.put(s3,"天津");

        // 遍历TreeMap集合,打印每个学生的信息

          tm.forEach(

                  (Student key, String value)->{

                      System.out.println(key + "---" + value);

                  }

          )

      }

  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值