Java-集合

集合框架图

image-20230107163106582

Collection接口和常用方法

image-20230107163003412


Collection接口常用方法,以实现子类ArrayList来演示

image-20230107162811332

package cn.meowrain.collection_;

import java.util.ArrayList;
import java.util.List;

public class CollectionMethod {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("jack");
        list.add("meowrain");
        list.add("hello");
        System.out.println("初始元素: " + list);
        System.out.println("--------------------");
        //用索引删除,返回的是删除的对象
        //用对象名删除,返回的是一个布尔值,删除成功返回true,删除失败返回false
        System.out.println("删除的元素是:" + list.remove(0) + " " + "\n 当前的元素为:" + list);
        System.out.println("----------------------");
        System.out.println("删除状态:" + list.remove("hello") + " " + "\n 当前的元素为:" + list);
        System.out.println("----------------------");
        //size返回元素个数
        System.out.println("当前List中的元素个数:" + list.size());

        //返回list中是否含有某元素
        System.out.println("list中是否含有 meowrain 这个元素" + list.contains("meowrain"));
        System.out.println("---------------------");
        //clean 清空整个表
        System.out.println("接下来使用clear操作清空list");
        list.clear();
        System.out.println("当前List中的元素个数:" + list.size());

        //isEmpty
        System.out.println("判断当前表是否为空:" + list.isEmpty());

        //addAll添加多个元素
        List list2 = new ArrayList();
        list2.add("红楼梦");
        list2.add("三国");
        list2.add("nice");
        list.addAll(list2);
        System.out.println("addAll后的list: " + list);
        System.out.println(" --------------");
        //containsAll
        System.out.println("containsAll");
        List list3 = new ArrayList();
        list3.add("nice");
        list3.add("三国");
        list.containsAll(list3); // true

        //removeAll
        System.out.println("-------------");
        List list4 = new ArrayList();
        list4.add("nice");
        list4.add("三国");
        list.removeAll(list4);
        System.out.println("removeAll后的list: " + list);

    }
}

image-20230107165111166

Collection接口遍历元素的方式

Iterator迭代器

image-20230107165224601

在调用iterator.next()方法之前必须调用iterator.hasNext()进行检测,若不调用,且下一条记录无效,直接调用it.next()会抛出NoSuchElementException异常

image-20230107165859984

package cn.meowrain.collection_;

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

public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Collection col = new ArrayList();
        col.add(new Book("三国演义","罗贯中",10.1));
        col.add(new Book("小李飞刀","古龙",5.1));
        col.add(new Book("红楼梦","曹雪芹",34.6));
//        System.out.println("col = "+ col);
        //现在希望能够遍历col集合
        //先得到col对应的迭代器
        Iterator iterator = col.iterator();
        //使用while循环遍历即可
        while(iterator.hasNext()){ //判断是否还有数据
            //返回下一个元素,类型是Object
            Object obj = iterator.next();
            System.out.println(obj);
        }
        /*
        *
        *   Book{name='三国演义', author='罗贯中', price=10.1}
            Book{name='小李飞刀', author='古龙', price=5.1}
            Book{name='红楼梦', author='曹雪芹', price=34.6}
        * */
    }
}
class Book {
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

image-20230107170941425

增强for循环

//增强for也能用在数组上
int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int num : nums) {
    System.out.print(num + " ");//1 2 3 4 5 6 7 8 9 10 
}

在Collection集合上的应用

package cn.meowrain.collection_;

import java.util.ArrayList;
import java.util.Collection;

public class CollectionFor {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Collection col = new ArrayList();
        col.add(new Book("三国演义", "罗贯中", 10.1));
        col.add(new Book("小李飞刀", "古龙", 5.1));
        col.add(new Book("红楼梦", "曹雪芹", 34.6));

        //使用增强for循环,for循环底层,仍然是迭代器,可以理解成简化版本的迭代器

        for (Object book : col) {
            System.out.println(book);
        }
        /*
        * Book{name='三国演义', author='罗贯中', price=10.1}
            Book{name='小李飞刀', author='古龙', price=5.1}
            Book{name='红楼梦', author='曹雪芹', price=34.6}
        *
        * */

        

    }
}

快捷方式;输入Iimage-20230107171713183

image-20230107171747708

课堂练习

image-20230107171914554

package cn.meowrain.collection_;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CollectionExercise {
    public static void main(String[] args) {
        Dog dog1 = new Dog("mike", 1);
        Dog dog2 = new Dog("john", 4);
        Dog dog3 = new Dog("cookie", 5);
        List<Dog> list = new ArrayList<>();
        list.add(dog1);
        list.add(dog2);
        list.add(dog3);
        //迭代器方法
        System.out.println("----------普通迭代器方法----------");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(next);
        }

        //增强for循环方法
        System.out.println("----------增强for循环方法----------");
        for (Dog dog : list) {
            System.out.println(dog);
        }
    }
}

class Dog {
    String name;
    int age;

    public Dog(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 String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

image-20230107172607316

List接口

List接口是Collection接口的子接口

package cn.meowrain.collection_;

import java.util.ArrayList;
import java.util.List;


public class List_ {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("jack");
        list.add("tom");
        list.add("mary");
        list.add("hsp");
        list.add("meowrain");
        list.add("meowrain"); //可以重复
        System.out.println(list);//顺序表
        //索引从0开始
        System.out.println(list.get(1));

    }
}

List接口的常用方法:

List接口常用方法

package cn.meowrain.collection_;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListExercise {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 12; i++) {
            list.add("hello" + i);
        }
        list.add(1, "韩顺平教育");
        String num5_string = list.get(4);
        list.remove(5);
        list.set(6, "meowrainyyds");
        Iterator<String> iterator = list.iterator();
        System.out.println("第5个元素:" + num5_string);
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }


    }
}

List的三种遍历方式

package cn.meowrain.collection_;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class ListFor {
    public static void main(String[] args) {
        //iterator
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            list.add("nice" + i);
        }
        //遍历
        System.out.println("==========Iterator============");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String next =  iterator.next();
            System.out.println(next);
        }
        //增强for循环
        System.out.println("==========增强for============");
        for (String s : list) {
            System.out.println(s);
        }
        //普通for循环
        System.out.println("==========普通for循环============");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }



    }
}

练习题

ArrayList方法
ListExercise2.java

package cn.meowrain.collection_;

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class ListExercise2 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List<Book> list = new ArrayList<>();
        list.add(new Book("西游记", "吴承恩", 100));
        list.add(new Book("三国演义", "罗贯中", 10.1));
        list.add(new Book("小李飞刀", "古龙", 5.1));
        list.add(new Book("红楼梦", "曹雪芹", 34.6));
        list.add(new Book("三体", "刘慈欣", 51));

        //排序
        Bubble_sort(list);
        //遍历输出
        Iterator<Book> iterator = list.iterator();
        while (iterator.hasNext()) {
            Book next = iterator.next();
            System.out.println(next);
        }
    }

    public static void Bubble_sort(List<Book> list) {
        //遍历list
        int size = list.size();
        for (int i = 0; i < size - 1; i++) {
            for (int j = 0; j < size - 1 - i; j++) {
                //取出对象
                Book book1 = list.get(j);
                Book book2 = list.get(j + 1);
                if (book1.getPrice() > book2.getPrice()) {
                    list.set(j, book2);
                    list.set(j + 1, book1);
                }

            }
        }
    }
}

Book.java

package cn.meowrain.collection_;

public class Book {
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "书名='" + name + '\'' +
                ", 作者='" + author + '\'' +
                ", 价格=" + price +
                '}';
    }

}

输出结果

ArrayList注意事项

ArrayList是线程不安全的,可以看源码,没有synchronized

ArrayList底层结构和源码分析