Java的集合

1. 集合类体系结构

在这里插入图片描述

2. Collection集合概述和使用

2.1 Collection集合概述

  • 是单列集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素
  • JDk不提供此接口的任何直接实现,它提供更具体的子接口实现

2.2 创建Collection集合的对象

  • 多态的方式
  • 具体的实现类ArrayList

2.3 Collection集合常用方法

方法名说明
对象名.add()添加元素
对象名.remove()从集合中移除指定的元素
对象名.clear()清空集合的元素
对象名.contains()判断集合中是否存在指定的元素
对象名.isEmpty()判断集合是否为空
对象名.size()集合的长度,也就是集合中元素的个数
Collection<String> c = new ArrayList<String>();
System.out.println(c.add("hello"));  // true 添加成功,返回true
System.out.println(c.add("world"));  // true
System.out.println(c.add("china"));  // true
System.out.println(c.add("hello"));  // true 允许添加重复内容
System.out.println(c);  // [hello, world, china, hello]
System.out.println(c.remove("china"));  // true
System.out.println(c.remove("guangdong"));  // false
System.out.println(c);  // [hello, world, hello]
System.out.println(c.contains("hello"));  // true
System.out.println(c.contains("guangdong"));  // false
System.out.println(c.isEmpty());  // false
System.out.println(c.size());  // 3
c.clear();  // 这个操作没有返回值
System.out.println(c);  // []

2.4 Collection集合的遍历

Iterator:迭代器,集合的专用遍历方法

Collection<String> c = new ArrayList<String>();
c.add("hello");
c.add("world");
c.add("china");
Iterator<String> it = c.iterator();
while (it.hasNext()) {
    String s = it.next();
    System.out.println(s);
}

3. List集合概述和特点

3.1 List集合概述

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

3.2 List集合特点

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

3.3 List集合特有方法

方法名说明
对象名.add()在此集合中的指定位置插入指定的元素
对象名.remove()删除指定索引的元素,返回被删除的元素
对象名.set()修改指定索引的元素,返回被修改的元素
对象名.get()返回指定索引的元素
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
System.out.println(list);  // [hello, world]
list.add(1, "china");
System.out.println(list);  // [hello, china, world]
System.out.println(list.remove(1));  // china
System.out.println(list);  // [hello, world]
System.out.println(list.set(1, "buddha"));  // world
System.out.println(list);  // [hello, buddha]
System.out.println(list.get(1));  // buddha
System.out.println(list);  // [hello, buddha]

3.4 List迭代器

  • 对象名.listIterator()方法得到List迭代器
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("china");
System.out.println(list);  // [hello, world, china]
ListIterator<String> sit = list.listIterator();
// 正向迭代
while (sit.hasNext()) {
    String s = sit.next();
    System.out.println(s);
}
// 逆向迭代
while (sit.hasPrevious()) {
    String p = sit.previous();
    System.out.println(p);
}

3.5. LinkedList集合特有的功能

方法名说明
对象名.addFirst()在该列表开头插入指定的元素
对象名.addLast()在该列表末尾插入指定的元素
对象名.getFirst()返回此列表中的第一个元素
对象名.getLast()返回此列表中的最后一个元素
对象名.removeFirst()从此列表中删除并返回第一个元素
对象名.removeLast()从此列表中删除并返回最后一个元素
LinkedList<String> ll = new LinkedList<String>();
System.out.println(ll.add("c"));  // true
System.out.println(ll.add("d"));  // true
System.out.println(ll);  // [c, d]
ll.addFirst("b");
System.out.println(ll);  // [b, c, d]
ll.addLast("e");
System.out.println(ll);  // [b, c, d, e]
System.out.println(ll.getFirst());  // b
System.out.println(ll.getLast());  // e
System.out.println(ll.removeFirst());  // b
System.out.println(ll.removeLast());  // e
System.out.println(ll);  // [c, d]

4. Set集合概述和特点

Set集合特点

  • 主要有HashSet和TreeSet两大实现类

    • HashSet是哈希表结构,主要利用HashMap的key来存储元素,计算插入元素的hashCode来获取元素在集合中的位置
    • TreeSet是红黑树结构,每一个元素都是树中的一个节点,插入的元素都会进行排序
  • 没有重复元素的集合

    • 在判断重复元素的时候,Set集合会调用hashCode()和equal()方法来实现
  • 元素无序的集合

// 创建集合对象
Set<String> set = new HashSet<>();
// 添加元素
set.add("hello");
set.add("world");
set.add("china");
// 遍历
for (String s : set) {
    System.out.println(s);
}

4.1 哈希值

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

Object类中有一个方法可获取对象的哈希值

  • 对象名.hashCode()

对象哈希值的特点

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

4.2 HashSet集合概述和特点

HashSet集合特点

  • 底层数据结构是哈希表
  • 集合元素的存取顺序会不一致
  • 没有索引的方法,不能使用普通for循环遍历
  • 不包含重复元素的集合
HashSet<String> hashSet = new HashSet<>();
hashSet.add("hello");
hashSet.add("world");
hashSet.add("china");
hashSet.add("hello");
System.out.println(hashSet.size());  // 3
for (String s : hashSet) {
    System.out.println(s);
}

4.3 LinkedHashSet集合概述和特点

LinkedHashSet集合特点

  • 哈希表和链表实现的Set接口,具有可预测的迭代次序
  • 有链表保证元素次序,元素的存取顺序是一致的
  • 由哈希表保证元素唯一,集合中没有重复的元素
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("hello");
linkedHashSet.add("world");
linkedHashSet.add("china");
linkedHashSet.add("hello");
System.out.println(linkedHashSet.size());  // 3
for (String s : linkedHashSet) {
    System.out.println(s);
}

4.4 TreeSet集合概述和特点

TreeSet集合特点

  • 元素有序,这里的顺序不是指存取顺序,而是按照一定的规则进行排序,具体排序方式取决于构造方法
    • TreeSet():无参构造,根据其元素的自然排序进行排序
    • TreeSet(Comparator comparator):根据指定的比较器进行排序
  • 没有带索引的方法,所以不能使用普通for循环遍历
  • 由于是Set集合,所以不包含重复元素集合
4.4.1 无参构造
TreeSet<Integer> integerTreeSet = new TreeSet<Integer>();
integerTreeSet.add(10);
integerTreeSet.add(50);
integerTreeSet.add(30);
integerTreeSet.add(10);
integerTreeSet.add(20);
System.out.println(integerTreeSet);  // [10, 20, 30, 50]
for (Integer i : integerTreeSet) {
    System.out.println(i);
}
4.4.2 有参构造(按照年龄升序排序)
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 o) {
        int i = this.getAge() - o.getAge();
        return i;
    }
}
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        TreeSet<Student> studentTreeSet = new TreeSet<Student>();

        Student s1 = new Student("林青霞", 20);
        Student s2 = new Student("王祖贤", 18);
        Student s3 = new Student("刘嘉玲", 30);

        studentTreeSet.add(s1);
        studentTreeSet.add(s2);
        studentTreeSet.add(s3);

        for (Student s : studentTreeSet) {
            System.out.println(s.getName() + s.getAge());
        }
    }
}
4.4.2 有参构造(按照年龄升序排序,年龄相同再按照姓名字母升序排序)
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 o) {
        int i = this.getAge() - o.getAge();
        int num2 = i == 0 ? this.getName().compareTo(o.getName()) : i;
        return num2;
    }
}
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        TreeSet<Student> studentTreeSet = new TreeSet<Student>();

        Student s1 = new Student("林青霞", 20);
        Student s2 = new Student("王祖贤", 18);
        Student s3 = new Student("刘嘉玲", 30);
        Student s4 = new Student("刘德华", 20);

        studentTreeSet.add(s1);
        studentTreeSet.add(s2);
        studentTreeSet.add(s3);
        studentTreeSet.add(s4);

        for (Student s : studentTreeSet) {
            System.out.println(s.getName() + s.getAge());
        }
    }
}
4.4.3 有参构造(按照年龄升序排序,年龄相同再按照姓名字母升序排序)
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        TreeSet<Student> studentTreeSet = new TreeSet<Student>();

        Student s1 = new Student("林青霞", 20);
        Student s2 = new Student("王祖贤", 18);
        Student s3 = new Student("刘嘉玲", 30);
        Student s4 = new Student("刘德华", 20);

        studentTreeSet.add(s1);
        studentTreeSet.add(s2);
        studentTreeSet.add(s3);
        studentTreeSet.add(s4);

        for (Student s : studentTreeSet) {
            System.out.println(s.getName() + s.getAge());
        }
    }
}
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        TreeSet<Student> studentTreeSet = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int i = o1.getAge() - o2.getAge();
                int num = i == 0 ? o1.getName().compareTo(o2.getName()) : i;
                return num;
            }
        });

        Student s1 = new Student("林青霞", 20);
        Student s2 = new Student("王祖贤", 18);
        Student s3 = new Student("刘嘉玲", 30);
        Student s4 = new Student("刘德华", 20);

        studentTreeSet.add(s1);
        studentTreeSet.add(s2);
        studentTreeSet.add(s3);
        studentTreeSet.add(s4);

        for (Student s : studentTreeSet) {
            System.out.println(s.getName() + s.getAge());
        }
    }
}

5. 增强for循环

简化数组和Collection集合的遍历。其内部原理是一个迭代器。

for(元素数据类型 变量名:数组或Collection集合) {
    // 在此处使用变量即可,该变量就是元素
}
// 数组代表
int[] number = {1, 2, 3};
for (int i : number) {
    System.out.println(i);
}
// 集合代表
Collection<String> c = new ArrayList<String>();
c.add("hello");
c.add("world");
c.add("china");
for (String s : c) {
    System.out.println(s);
}

6. 数据结构

栈:是一种数据先进后出的模型

队列:是一种数据先进先出的模型

数组:是一种查询快、增删慢的模型

链表:是一种增删快、查询慢的模型

哈希表:提供很快速的插入和查找操作(有的时候甚至删除操作也是)

7. 泛型

7.1 泛型概述

泛型本质是参数化类型。由原来的具体的类型参数化,然后在使用/调用时传入具体的类型

7.2 泛型类

泛型类的定义格式

格式:修饰类 class 类型<类型> {}

范例:public class Generic {}

  • E表示集合的元素类型

  • K 和 V分别表示表的关键字与值的类型

  • T(需要时还可以用临近的字母 U 和 S)表示“任意类型”

public class Generic<T> {
    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}
public class Demo {
    public static void main(String[] args) {
        Generic<String> name = new Generic<String>();
        name.setT("王宝强");
        System.out.println(name.getT());
        Generic<Integer> age = new Generic<Integer>();
        age.setT(28);
        System.out.println(age.getT());
    }
}

7.3 泛型方法

泛型方法的定义格式

格式:修饰符 <类型> 返回值类型 方法名 (<类型> 变量名) {}

范例:public void show(T t) {}

public class Generic<T> {
    public <T> void show(T t) {
        System.out.println(t);
    }
}
public class Demo {
    public static void main(String[] args) {
        Generic<String> g1 = new Generic<String>();
        g1.show("hello");
        Generic<Integer> g2 = new Generic<Integer>();
        g2.show(18);
    }
}

7.4 泛型接口

泛型接口的定义格式

格式:修饰符 interface 接口名 <类型> {}

范例:public interface Generia {}

public interface showInterface<T> {
    public void show(T t);
}
public class Generic implements showInterface<String> {
    @Override
    public void show(String s) {
        System.out.println(s);
    }
}
public class Demo {
    public static void main(String[] args) {
        Generic g = new Generic();
        g.show("hello world");
    }
}

7.5 类型通配符

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

  • 类型通配符:<?>
  • List<?>:表示匹配任何的类型
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<?> list1 = new ArrayList<Object>();
        List<?> list2 = new ArrayList<Number>();
        List<?> list3 = new ArrayList<Integer>();
    }
}

只希望代表某些类型的父类,可以使用类型通配符的上限

  • 类型通配符上限:<? extends 类型>
  • List<? extends Number>:表示的类型是Number或者子类型
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<? extends Number> list1 = new ArrayList<Number>();
        List<? extends Number> list2 = new ArrayList<Integer>();
    }
}import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<? extends Number> list1 = new ArrayList<Number>();
        List<? extends Number> list2 = new ArrayList<Integer>();
    }
}

只希望代表某些类型的子类,可以使用类型通配符的下限:

  • 类型通配符下限:<? super 类型>
  • List<? super Number>:表示类型是Number或者父类型
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<? super Number> list1 = new ArrayList<Number>();
        List<? super Number> list2 = new ArrayList<Object>();
    }
}

7.6 可变参数

可变参数,就是在定义的时候参数个数不确定,调用的时候才确定

格式:修饰符 返回值类型 方法名(数据类型 …变量名){}

示例:public static int sum (int …a){}

注意项:

  • 这里的变量是一个数组
  • 如果多个参数,可变参数要放在最后
public class Demo {
    public static void main(String[] args) {
        int sum = sum(1, 2);
        System.out.println(sum);
    }

    public static int sum(int ...a) {
        int sum = 0;
        for (int i : a) {
            sum += i;
        }
        return sum;
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class Demo {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("hello", "world", "china");
        System.out.println(list1);
        List<String> list2 = List.of("hello", "world", "china");
        System.out.println(list2);
        Set<String> list3 = Set.of("hello", "world", "china");
        System.out.println(list3);
    }
}

8. Map集合概述和使用

Map集合概述

  • Interface Map<K, V>
    • K:键的类型
    • V:值的类型
  • 将键映射到值的对象,不能包含重复的键,每个键可以映射到最多一个值

8.1 Map集合的基本功能

方法名说明
put(K key, V value)添加元素
remove(Object key)根据键删除键值对元素
clear()移除所有键值对元素
containsKey(Object key)判断集合是否包含指定的键
containsValue(Object value)判断集合是否包含指定的值
isEmpty()判断集合是否为空
size()集合键值对个数
Map<String, String> map = new HashMap<String, String>();
map.put("001", "林青霞");
map.put("002", "张曼玉");
map.put("003", "王祖贤");
map.put("003", "张柏芝");
System.out.println(map);  // {001=林青霞, 002=张曼玉, 003=张柏芝}
System.out.println(map.containsKey("003"));  // true
System.out.println(map.containsValue("林青霞"));  // true
System.out.println(map.isEmpty());  // false
System.out.println(map.size());  // 3
System.out.println(map.remove("003"));  // 张柏芝
map.clear();
System.out.println(map);  // {}

8.2 Map集合的获取功能

方法名说明
get(Object key)根据键获取值
keySet()获取所有的集合
value()获取所有值的集合
entrySet()获取所有键值对对象的集合
Map<String, String> map = new HashMap<String, String>();
map.put("001", "林青霞");
map.put("002", "张曼玉");
map.put("003", "王祖贤");
System.out.println(map);  // {001=林青霞, 002=张曼玉, 003=张柏芝}
System.out.println(map.get("001"));  // 林青霞
Set<String> keySet = map.keySet();
System.out.println(keySet);  // [001, 002, 003]
Collection<String> values = map.values();
System.out.println(values);  // [林青霞, 张曼玉, 王祖贤]
// 遍历
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> me : entries) {
    String key = me.getKey();
    String value = me.getValue();
    System.out.println(key + ":" + value);
}

9. Collections概述和使用

Collections是一个操作Set、List和Map等集合的工具类。Collections中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法

List<Integer> nums = new ArrayList<Integer>();
nums.add(50);
nums.add(10);
nums.add(40);
nums.add(30);
Collections.sort(nums);
System.out.println(nums);  // [10, 30, 40, 50]
Collections.reverse(nums);
System.out.println(nums);  // [50, 40, 30, 10]
Collections.shuffle(nums);
System.out.println(nums);  // [50, 40, 10, 30]
public class Student {
    private int age;
    private String name;

    public Student() {
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Demo {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<Student>();
        Student s1 = new Student(25, "林青霞");
        Student s2 = new Student(32, "张曼玉");
        Student s3 = new Student(18, "王祖贤");
        list.add(s1);
        list.add(s2);
        list.add(s3);
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int i = o1.getAge() - o2.getAge();
                return i == 0 ? o1.getName().compareTo(o2.getName()) : i;
            }
        });
        for (Student s: list) {
            System.out.println(s.getName() + s.getAge());
        }
    }
}
王祖贤18
林青霞25
张曼玉32
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员buddha

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值