集合:Collection接口,List接口,ArrayList类,Set接口,TreeSet类,比较器

集合

集合与数组的区别:

  • 数组:长度一旦确定不可改变;存储的数据类型要求相同;有序,索引为0~length-1
  • 集合:长度根据数据的多少动态的伸缩;可以存储任意类型的数据

1. 手写简易版容器

手写简易版容器,实现数据的增删查改,具体代码如下:

import java.util.Arrays;
//尝试实现自定义容器类中的删除,修改,查询的方法
public class ContainerTest {
    public static void main(String[] args) {
        //创建一个容器对象
        MyContainer my = new MyContainer();
        //存储数据
        my.add("zhangsan");
        System.out.println(my.size());
        System.out.println(my);
        my.add("lisi");
        System.out.println(my.size());
        System.out.println(my);
        my.add("wangwu");
        System.out.println(my.size());
        System.out.println(my);
        //删除数据
        my.delete("wangwu");
        System.out.println(my.size());
        System.out.println(my);
        //得到查询数据的索引
        my.serch("lisi");
        //修改数据
        my.modify("lisi","wangwu");
        System.out.println(my);
    }
}
//自定义容器类
class MyContainer{
    //内部存储数据的数组结构
    private String[] arr;
    //记录容器中存储的数据个数
    private int size;
    //构造器
    public MyContainer(){}
    //增
    public void add(String value) {
        //第一次添加
        if(arr==null || size==0){
            arr = new String[1];
            arr[0] = value;
        }else{
            //备份原数组
            String[] temp = arr;
            //创建新数组 原有长度基础之上+1
            arr = new String[size+1];
            for(int i=0;i<size;i++){
                arr[i] = temp[i];
            }
            arr[size] = value;
        }
        size++;
    }
    //删
    public void delete(String value){
        int a = 0;
        //得到要删除的字符串的索引
        for (int i=0;i<size;i++){
            if (value.equals(arr[i])){
                a = i;
            }
        }
        //备份原数组
        String[] temp = arr;
        //创建新数组,长度-1
        arr = new String[size-1];
        for(int i=0;i<size;i++){
            //索引小于删除字符串的索引,直接拷贝
            if (i<a){
                arr[i] = temp[i];
            //索引大于删除字符串的索引,跳过删除字符串的索引删除
            }else if(i>a){
                arr[i] = temp[i+1];
            }
        }
        size--;
    }
    //查
    public void serch(String value){
        int a = 0;
        for (int i=0;i<size;i++){
            if (value.equals(arr[i])){
                a = i;
            }
        }
        System.out.println(value+"的索引为:"+a);
    }
    //改
    public void modify(String value1,String value2){
        for (int i=0;i<size;i++){
            if (value1.equals(arr[i])){
                arr[i] = value2;
            }
        }
    }
    //获取容器中数据的个数
    public int size(){
        return this.size;
    }

    @Override
    public String toString() {
        return Arrays.toString(arr);
    }
}

2. Collection接口

Collection接口的常用方法及两种遍历方式:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

//Collection类常用方法
public class CollectionDemo {
    public static void main(String[] args) {
        Collection col1 = new ArrayList();
        Collection col2 = new ArrayList();
        //add(E e) 确保此集合包含指定的元素
        col1.add("abc");
        col1.add(123);
        col1.add(true);
        System.out.println(col1);
        //addAll(Collection<? extends E> c) 将指定集合中的所有元素添加到此集合中
        col2.addAll(col1);
        System.out.println(col2);
        //clear() 从此集合中删除所有元素(可选操作)
        col2.clear();
        System.out.println(col2);
        //contains(Object o) 如果此collection包含指定的元素,则返回true
        System.out.println(col1.contains(123));
        //containsAll(Collection<?> c) 如果此集合包含指定集合中的所有元素,则返回 true
        col2.add("abc");
        col2.add(123);
        System.out.println(col1.containsAll(col2));
        //equals(Object o) 将指定对象与此集合进行比较以获得相等性
        col2.add(true);
        System.out.println(col1.equals(col2));
        //isEmpty() 如果此集合不包含任何元素,则返回 true
        System.out.println(col1.isEmpty());
        //remove(Object o) 从此集合中移除指定元素的单个实例(如果存在)
        col2.remove(123);
        System.out.println(col2);
        //removeAll(Collection<?> c) 删除此集合的所有元素,这些元素也包含在指定的集合中
        col1.removeAll(col2);
        System.out.println(col1);
        //size() 返回此集合中的元素数
        System.out.println(col1.size());
        //retainAll(Collection<?> c) 仅保留此集合中包含在指定集合中的元素
        col1.add("abc");
        col2.retainAll(col1);
        System.out.println(col2);
        //toArray() 返回包含此集合中所有元素的数组
        col1.add('c');
        col1.add('d');
        Object[] obj = col1.toArray();
        System.out.println(Arrays.toString(obj));

        //两种遍历方法
        //1.增强for循环
        for (Object o:col1){
            System.out.println(o);
        }

        //2.iterator迭代器遍历
        //获取迭代器对象
        Iterator it = col1.iterator();
        //判断是否存在下一个元素
        while (it.hasNext()){
            //获取下一个元素
            System.out.println(it.next());
        }
    }
}

3. List接口

List是一个有序可重复的容器,接口中新增了一些可以根据索引操作的方法。

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ListDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("zhangsan");
        list.add("lisi");
        list.add("zhangsan");
        //add(int index, E element) 将指定元素插入此列表中的指定位置
        list.add(1,"wangwu");
        System.out.println(list);
        //get(int index) 返回此列表中指定位置的元素
        System.out.println(list.get(1));
        //indexOf(Object o) 返回此列表中第一次出现的指定元素的索引,如果此列表不包含该元素,则返回-1
        System.out.println(list.indexOf("zhangsan"));
        System.out.println(list.lastIndexOf("zhangsan"));
        //remove(int index) 删除此列表中指定位置的元素
        list.remove(1);
        System.out.println(list);
        //set(int index, E element) 用指定的元素替换此列表中指定位置的元素
        list.set(2,"wangwu");
        System.out.println(list);
        //of(E... elements) 返回包含任意数量元素的不可修改列表
        List list1 = List.of(list);
        System.out.println(list1);
        
        //List的遍历方式除了增强for循环和迭代器遍历外,还可以使用普通for循环和列表迭代器
        //普通for循环
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
        //列表迭代器 从前往后遍历
        ListIterator<String> it = list.listIterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //列表迭代器 从后往前遍历
        while (it.hasPrevious()){
            System.out.println(it.previous());
        }
    }
}

4. ArrayList类

ArrayList类是List接口的实现类,底层结构是可变数组。有以下特点:

  • 优点:根据索引查询修改效率高
  • 缺点:做增加删除操作时效率低
  • 应用场景:大量做查询,少量做增删时适合使用ArrayList
  • 扩容机制:每次扩容原容量的1.5倍

Vector类也是通过数组存储数据的,与ArrayList特点相同,同时也有着区别:

  • 线程安全(ArrayList线程不安全)
  • Vector每次扩容原容量的2倍

练习:

import java.util.ArrayList;
import java.util.List;
//使用ArrayList添加员工信息,年龄大于25岁的降薪1000,薪资大于10000的解雇
public class ArrayListDemo {
    public static void main(String[] args) {
        List<Employee> list = new ArrayList<>();
        Employee e1 = new Employee("张三",20,12000);
        Employee e2 = new Employee("李四",22,9000);
        Employee e3 = new Employee("王五",26,11000);
        list.add(e1);
        list.add(e2);
        list.add(e3);
        for (int i=0;i<list.size();i++){
            //判断年龄是否大于25
            if (list.get(i).getAge()>25){
                //薪资-1000
                list.get(i).setSalary(list.get(i).getSalary()-1000);
            }
            //判断薪资是否大于10000
            if (list.get(i).getSalary()>10000){
                //删除该数据
                list.remove(i);
            }
        }
        System.out.println(list);//[Employee{name='李四', age=22, salary=9000.0}, Employee{name='王五', age=26, salary=10000.0}]
    }
}

class Employee{
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    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 double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
	//重写toString方法
    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

5. Set接口

Set是无序不可重复的接口,没有新增的方法。无序指的是存储数据的顺序与添加的顺序不同,系统有着自己的算法。

代码:

import java.util.HashSet;
import java.util.Set;
public class SetDemo {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        //测试Set无序存储数据
        set.add("哈哈");
        set.add("嘿嘿");
        set.add("你好");
        set.add("谢谢");
        set.add("不客气");
        set.add("早上好");
        set.add("晚安");
        System.out.println(set);//[谢谢, 晚安, 你好, 早上好, 哈哈, 嘿嘿, 不客气]
    }
}

6. TreeSet类

TreeSet:

  • 底层结构:红黑树(平衡二叉树)
  • 特点:有序(存储数据默认升序),存放的顺序与内部存储的顺序不同

代码:

import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo {
    public static void main(String[] args) {
        //测试Integer数据的升序存储
        TreeSet<Integer> set1 = new TreeSet<>();
        set1.add(5);
        set1.add(2);
        set1.add(7);
        System.out.println(set1);//[2, 5, 7]
		//测试字符串的升序存储
        Set<String> set2 = new TreeSet<>();
        set2.add("张三");
        set2.add("王五");
        set2.add("李四");
        set2.add("哈哈");
        set2.add("锤子");
        System.out.println(set2);//[哈哈, 张三, 李四, 王五, 锤子]
    }
}

7. 比较器

当存储自定义的引用数据类型数据时,去重排序都要求实现比较器,具体步骤是:先判断是否存在外部比较器可比较存储数据的大小,如果有使用外部比较器;如果没有看存储的数据类型是否存在默认的内部比较器,如果存在使用内部比较器比较数据的大小;如果都不存在抛出异常ClassCastException。

7.1 内部比较器

内部比较器即自然排序,需要比较的引用数据类型的类实现Comparable接口,重写CompareTo方法,在方法中自定义比较规则。

代码:

import java.util.TreeSet;
//测试内部比较器
public class TreeSetDemo02 {
    public static void main(String[] args) {
        Employee e1 = new Employee("张三",20,12000);
        Employee e2 = new Employee("李四",22,9000);
        Employee e3 = new Employee("王五",26,11000);
        Employee e4 = new Employee("赵六",24,15000);
        TreeSet<Employee> set = new TreeSet<>();
        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        System.out.println(set);
    }
}
//定义类实现Comparable接口
class Employee implements Comparable<Employee>{
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    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 double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
	//重写compareTo方法,返回当前对象与比较对象的差,就为升序排序,反之则为降序排序,相等的话能达到去重的目的
    @Override
    public int compareTo(Employee o) {
        return this.getAge()-o.getAge();
    }
}

7.2 外部比较器

外部比较器即定制排序,自定义类实现Comparator接口,重写compare方法,方法中定义规则。

代码:

import java.util.Comparator;
import java.util.TreeSet;
//测试外部比较器(Employee类就不重新定义了)
public class TreeSetDemo03 {
    public static void main(String[] args) {
        Employee e1 = new Employee("张三",20,12000);
        Employee e2 = new Employee("李四",22,9000);
        Employee e3 = new Employee("王五",26,11000);
        Employee e4 = new Employee("赵六",24,15000);
        //使用外部比较器
        TreeSet<Employee> set = new TreeSet<>(new outComparator());
        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        System.out.println(set);
    }
}
//定义外部比较器:定义类实现Comparator接口,泛型为需要比较的类型
class outComparator implements Comparator<Employee>{
    //重写compare方法,返回o1与o2的差,即为升序排序,反之则为降序,相等的话能实现去重的目的
    @Override
    public int compare(Employee o1, Employee o2) {
        return (int)(o1.getSalary()-o2.getSalary());
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值