Java面向对象之集合相关

1、集合

前面我们保存多个数据使用的是数组,那么数组有不足的地方

在这里插入图片描述

1.1、定义

在这里插入图片描述

1.2、集合的框架体系

Java 的集合类很多,主要分为两大类

  1. 集合主要是两组(单列集合,双列集合)
  2. Collection 接口有两个重要的子接口 List Set,他们的实现子类都是单列集合
  3. Map 接口的实现子类 是双列集合,存放的 key - value

在这里插入图片描述
在这里插入图片描述

package collection_;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"all"})
public class Collection_ {
    public static void main(String[] args) {
        // 1. 集合主要是两组(单列集合, 双列集合)
        // 2. Collection 接口有两个重要的子接口 List Set, 他们的实现子类都是单列集合
        // 3. Map 接口的实现子类 是双列集合, 存放的 key - value
        // Collection
        ArrayList arrayList = new ArrayList();
        arrayList.add("jack");
        arrayList.add("tom");
        System.out.println("arrayList=" + arrayList);  // arrayList=[jack, tom]

        // Map
        HashMap hashMap = new HashMap();
        hashMap.put("name", "allen");
        hashMap.put("age", 18);
        System.out.println("hashMap=" + hashMap);  // hashMap={name=allen, age=18}
    }
}
1.3、Collection 接口和常用方法
1.3.1、Collection 接口实现类的特点

在这里插入图片描述

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

package collection_;

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

@SuppressWarnings({"all"})
public class CollectionMethod {
    public static void main(String[] args) {
        // 以 ArrayList 实现类来演示
        List list = new ArrayList();
        // add: 添加单个元素
        list.add("jack");
        list.add(10);  // list.add(new Integer(10))
        list.add(true);
        System.out.println("list=" + list);  // list=[jack, 10, true]
        // remove: 删除指定元素
        list.remove(0);  // 删除第一个元素
        list.remove(true);  // 指定删除某个元素
        System.out.println("list=" + list);  // list=[10]
        // contains: 查找元素是否存在
        System.out.println(list.contains(10));  // true
        // size: 获取元素个数
        System.out.println(list.size());  // 1
        // isEmpty: 判断是否为空
        System.out.println(list.isEmpty());  // false
        // clear: 清空
        list.clear();
        System.out.println("list=" + list);  // list=[]
        // addAll: 添加多个元素
        List list2 = new ArrayList();
        list2.add("三国演义");
        list2.add("红楼梦");
        list.addAll(list2);
        System.out.println("list=" + list);  // list=[三国演义, 红楼梦]
        // containsAll: 查找多个元素是否都存在
        System.out.println(list.containsAll(list2));  // true
        // removeAll: 删除多个元素
        list.add("西游记");
        list.removeAll(list2);
        System.out.println("list=" + list);  // list=[西游记]
    }
}
1.3.2、Collection 接口遍历元素方式 1-使用 Iterator(迭代器)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

package collection_;

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

@SuppressWarnings({"all"})
public class CollectionIterator {
    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 集合
        // 1. 先得到 col 对应的 迭代器
        Iterator iterator = col.iterator();
        // 2. 使用 while 循环遍历
        while (iterator.hasNext()) {  // 判断是否还有数据
            // 返回下一个元素, 类型是 Object
            Object obj = iterator.next();
            System.out.println("obj=" + obj);
        }

        // 快捷键, 快速生成 while => itit
        // 显示所有的快捷键的的快捷键 ctrl + j
        // while (iterator.hasNext()) {
        //     Object next =  iterator.next();
        //     System.out.println("next=" + next);
        // }

        // 3. 当退出 while 循环后, 这时 iterator 迭代器, 指向最后的元素
        // iterator.next();  // NoSuchElementException

        // 4. 如果希望再次遍历, 需要重置我们的迭代器
        iterator = col.iterator();
        System.out.println("===第二次遍历===");
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println("obj=" + obj);
        }
    }
}

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 +
                '}';
    }
}
1.3.3、Collection 接口遍历对象方式 2-for 循环增强

在这里插入图片描述

1.3.4、小练习
  1. 创建 3 个 Dog {name, age} 对象,放入到 ArrayList 中,赋给 List 引用
  2. 用迭代器和增强 for 循环两种方式来遍历
  3. 重写 Dog 的 toString 方法,输出 name 和 age
package collection_;

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

@SuppressWarnings({"all"})
public class CollectionExercise {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Dog("小黑", 3));
        list.add(new Dog("大黄", 100));
        list.add(new Dog("大壮", 8));

        // 使用迭代器
        System.out.println("使用迭代器来遍历");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object dog = iterator.next();
            System.out.println("dog=" + dog);
        }

        // 使用增强 for
        System.out.println("使用增强 for 来遍历");
        for (Object dog : list) {
            System.out.println("dog=" + dog);
        }
    }
}

/**
 * 创建 3 个 Dog {name, age} 对象,放入到 ArrayList 中,赋给 List 引用
 * 用迭代器和增强 for 循环两种方式来遍历
 * 重写 Dog 的 toString 方法, 输出 name 和 age
 */
class Dog {
    private String name;
    private 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 +
                '}';
    }
}
1.4、List 接口和常用方法
1.4.1、List 接口基本介绍

在这里插入图片描述

package List;

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

@SuppressWarnings({"all"})
public class List_ {
    public static void main(String[] args) {
        // 1. List 集合类中元素有序(即添加顺序和取出顺序一致)、且可重复
        List list = new ArrayList();
        list.add("jack");
        list.add("tom");
        list.add("lily");
        list.add("king");
        list.add("mary");
        System.out.println("list=" + list);  // list=[jack, tom, lily, king, mary]

        // 2. List 集合中的每个元素都有其对应的顺序索引, 即支持索引
        System.out.println(list.get(2));  // lily
    }
}
1.4.2、List 接口的常用方法
package List;

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

@SuppressWarnings({"all"})
public class ListMethod {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("张三丰");
        list.add("贾宝玉");
        // void add(int index, Object ele): 在 index 位置插入 ele 元素
        // 在 index = 1 的位置插入一个对象 tom
        list.add(1, "tom");
        System.out.println("list=" + list);  // list=[张三丰, tom, 贾宝玉]

        // boolean addAll(int index, Collection eles): 从 index 位置开始将 eles 中的所有元素添加进来
        List list2 = new ArrayList();
        list2.add("jack");
        list2.add("king");
        list.addAll(1, list2);
        System.out.println("list=" + list);  // list=[张三丰, jack, king, tom, 贾宝玉]

        // Object get(int index): 获取指定 index 位置的元素
        System.out.println(list.get(2));  // king

        // int indexOf(Object obj): 返回 obj 在集合中首次出现的位置
        System.out.println(list.indexOf("tom"));  // 3

        // int lastIndexOf(Object obj): 返回 obj 在当前集合中末次出现的位置
        list.add("lily");
        System.out.println(list.lastIndexOf("lily"));  // 5

        // Object remove(int index): 移除指定 index 位置的元素, 并返回此元素
        list.remove(0);
        System.out.println("list=" + list);  // list=[jack, king, tom, 贾宝玉, lily]

        // Object set(int index, Object ele): 设置指定 index 位置的元素为 ele, 相当于是替换
        list.set(2, "lucy");
        System.out.println("list=" + list);  // list=[jack, king, lucy, 贾宝玉, lily]

        // List subList(int fromIndex, int toIndex): 返回从 fromIndex 到 toIndex 位置的子集合
        // 注意返回的子集合 fromIndex <= subList < toIndex
        List returnList = list.subList(0, 2);
        System.out.println("returnList=" + returnList);  // returnList=[jack, king]
    }
}
1.4.3、小练习

添加 10 个以上的元素(比如 String “hello” ),在 2 号位插入一个元素 “中国”
获得第 5 个元素,删除第 6 个元素,修改第 7 个元素,在使用迭代器遍历集合
要求:使用 List 的实现类 ArrayList 完成

package List;

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

@SuppressWarnings({"all"})
public class ListExercise {
    public static void main(String[] args) {
        /**
         * 添加 10 个以上的元素(比如 String "hello" ),在 2 号位插入一个元素 "中国"
         * 获得第 5 个元素,删除第 6 个元素,修改第 7 个元素,在使用迭代器遍历集合
         * 要求: 使用 List 的实现类 ArrayList 完成
         */
        List list = new ArrayList();
        for (int i = 0; i < 11; i++) {
            list.add("hello" + i);
        }
        System.out.println("list=" + list);  // list=[hello0, hello1, hello2, hello3, hello4, hello5, hello6, hello7, hello8, hello9, hello10]
        // 在 2 号位插入一个元素 "中国"
        list.add(1, "中国");
        System.out.println("list" + list);  // list[hello0, 中国, hello1, hello2, hello3, hello4, hello5, hello6, hello7, hello8, hello9, hello10]
        // 获得第 5 个元素
        System.out.println(list.get(4));  // hello3
        // 删除第 6 个元素
        list.remove(5);
        System.out.println("list=" + list);  // list=[hello0, 中国, hello1, hello2, hello3, hello5, hello6, hello7, hello8, hello9, hello10]
        // 修改第 7 个元素
        list.set(6, "hello world");
        System.out.println("list=" + list);  // list=[hello0, 中国, hello1, hello2, hello3, hello5, hello world, hello7, hello8, hello9, hello10]

        // 使用迭代器遍历集合
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println("obj=" + obj);
        }
    }
}
1.4.4、List 的三种遍历方式 [ArrayList, LinkedList,Vector]

在这里插入图片描述

package List;

import java.util.*;

@SuppressWarnings({"all"})
public class ListFor {
    public static void main(String[] args) {
        // List 接口的实现子类 Vector LinkedList
        // List list = new ArrayList();
        // List list = new Vector();
        List list = new LinkedList();
        list.add("jack");
        list.add("tom");
        list.add("king");
        list.add("lucy");
        // 遍历
        // 1. 迭代器
        System.out.println("=====迭代器=====");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println("obj=" + obj);
        }

        // 2. 增强 for
        System.out.println("=====增强 for=====");
        for (Object obj : list) {
            System.out.println("obj=" + obj);
        }

        // 3. 普通 for
        System.out.println("=====普通 for=====");
        for (int i = 0; i < list.size(); i++) {
            System.out.println("obj=" + list.get(i));
        }
    }
}
1.4.5、实现类的小练习

在这里插入图片描述

package List;

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

@SuppressWarnings({"all"})
public class ListExercise02 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Book("红楼梦", "曹雪芹", 100));
        list.add(new Book("西游记", "吴承恩", 10));
        list.add(new Book("水浒传", "施耐庵", 19));
        list.add(new Book("三国", "罗贯中", 80));
        list.add(new Book("西游记", "吴承恩", 7.5));

        // 对集合进行排序
        for (Object o : list) {
            System.out.println(o);
        }

        // 冒泡排序
        sort(list);
        System.out.println("=====排序后的结果=====");
        System.out.println("list=" + list);  // list=[Book{name='西游记', author='吴承恩', price=7.5}, Book{name='西游记', author='吴承恩', price=10.0}, Book{name='水浒传', author='施耐庵', price=19.0}, Book{name='三国', author='罗贯中', price=80.0}, Book{name='红楼梦', author='曹雪芹', price=100.0}]
    }

    // 静态方法
    // 价格要求是从小到大
    public static void sort(List list) {
        int intSize = list.size();
        for (int i = 0; i < intSize; i++) {
            for (int j = 0; j < intSize - 1 - i; j++) {
                // 取出对象 Book
                Book book1 = (Book) list.get(j);
                Book book2 = (Book) list.get(j + 1);
                if (book1.getPrice() > book2.getPrice()) {  // 需要交换
                    list.set(j, book2);
                    list.set(j + 1, book1);
                }
            }
        }
    }
}

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 +
                '}';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值