集合02 Collection - Java

在这里插入图片描述

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

Collection介绍

Collection接口实现类的特点: public interface Collection<E> extends Iterable<E>

  1. Collection的实现子类可以存放多个元素,每个元素可以是Object
  2. 有些Collection的实现类,可以存放重复的元素,有些不可以
  3. 有些Collection的实现类,有些是有序的(List),有些是无序(Set)
  4. Collection接口没有直接的实现子类,是通过它的子接口Set 和 List来实现的

Collection接口常用方法(1)

(因为接口本身不能被实例化),以它的实现子类ArrayList来掩饰。
接口本身不能被实例化,只有实现了这个接口的类才能被实例化。

  1. add:添加单个元素
    boolean add(E e);
  2. remove:删除指定元素
    E remove(int index);
    boolean remove(Object o);
  3. contains:查找元素是否存在
    boolean contains(Object o);
  4. size:获取元素个数
  5. isEmpty:判断是否为空
  6. clear:清空
  7. addAll:添加多个元素
  8. containsAll:查找多个元素是否都存在
  9. removeAll:删除多个元素
  10. 说明:以ArrayList实现类来演示
  • 演示
public class CollectionMethod {
    public static void main(String[] args) {
        //add:添加单个元素
        System.out.println("=================add====================");
        List list = new ArrayList();
        list.add("jack");
        list.add(12);//有一个自动装箱的过程 = list.add(new Integer(12))
        list.add(true);
        list.add(3,"haha");//在index为1的位置,添加element2
        //既可以用来添加,也可以用来修改。
        System.out.println("list = "+list);

        //remove:删除指定元素
        System.out.println("================remove==================");
        list.remove(3);
        list.remove("jack");
        System.out.println("list = "+list);

        //contains:查找元素是否存在
        System.out.println("================contains================");
        if(list.contains("jack")) {
            System.out.println("存在");
        } else{
            System.out.println("不存在");
        }

        //size:获取元素个数
        System.out.println("==================size==================");
        System.out.println(list.size());

        //isEmpty:判断是否为空
        System.out.println("================isEmpty=================");
        if(list.isEmpty()) {
            System.out.println("为空");
        } else {
            System.out.println("不为空");
        }

        //clear:清空
        System.out.println("=================clear==================");
        list.clear();
        System.out.println("list = " + list);

        //addAll:添加多个元素
        System.out.println("================addAll==================");
        ArrayList list2 = new ArrayList();
        list2.add("hongloumeng");
        list2.add("shuihuzhuan");
        list.addAll(list2);
        System.out.println(list);

        //containsAll:查找多个元素是否都存在
        list.add("liaozhai");
        System.out.println("==============containsAll===============");
        System.out.println(list.containsAll(list2));

        //removeAll:删除多个元素
        System.out.println("===============removeAll================");
        list.removeAll(list2);
        System.out.println("list = " + list);
        //说明:以ArrayList实现类来演示
    }

Collection接口遍历元素方式

(1)使用迭代器 Iterator

Collection接口,是Iterable的子接口。
Iterable接口中有一个方法 Iterator<T> iterator();
——Returns an iterator over elements of type {@code T}.

  1. Iterator对象称为迭代器,主要用于遍历Collection 集合中的元素。
  2. 所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象,即可以返回一个迭代器。
  3. Iterator的结构图。
  4. Iterator仅用于遍历集合,Iterator本身并不存放对象。
    在这里插入图片描述
    Iterator接口的方法:hasNext, next, remove
    注意:在调用 iterator .next()方法之前必须要调用iterator.hasNext()进行检测。若不调用,且下一条记录无效,直接调用iterator.next()会抛出NoSuchElementException异常。
  5. 当退出while循环后,这时iterator迭代器,指向最后的元素
    it.next(); NoSuchElementException
  6. 如果希望再次遍历,需要重置我们的迭代器
    Iterator it = coll.iterator();
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

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

        Iterator it = coll.iterator();
        while(it.hasNext()) {
            Object obj = it.next();
            System.out.println("obj = " + obj);
            //这里的println,会调用obj的 toString方法
            //具体的toString要看 此时obj的运行类型有没有重写。
        }
//        快捷键 快速生成 ==> itit回车

		//当退出while循环后,这时iterator迭代器,指向最后的元素
        it.next();
        //如果希望再次遍历,需要重置我们的迭代器
        Iterator it = coll.iterator();

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

    //省略了setget方法

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

在这里插入图片描述

快捷键 快速生成 ==> itit 回车
显示所有的快捷键的的快捷键 ctrl + j

(2)使用增强for循环

增强for循环,可以代替iterator迭代器,特点:增强for就是简化版的iterator,本质一样。只能用于遍历集合或数组。

增强for用在集合和数组
底层依然是迭代器

基本语法

for(元素类型 元素名:集合名或者数组名) {
	访问元素
}
    public static void main(String[] args) {
        Collection coll = new ArrayList();//向上转型
        //ArrayList coll = new ArrayList();
        coll.add(new Book("三国演义","罗贯中",10.1));
        coll.add(new Book("小李飞刀","古龙",5.1));
        coll.add(new Book("红楼梦","曹雪芹",34.6));

//        增强for循环
        for(Object book : coll) {
            System.out.println("book="+book);
        }
//        增强for循环也可以在数组中使用
        int[] nums = {1,5,62,9,2};
        for (int i :nums) {
            System.out.println("i = "+i);
        }
    }

练习

请编写程序 CollectionExercise.java
1.创建3个Dog {name, age}对象,放入到 ArrayList中,赋给List引用
2.用迭代器和增强for循环两种方式来遍历
3.重写Dog的toString方法,输出name和age

List

Collection有 List子接口 和 Set子接口,上文是 Collection接口的一些方法(只是用了 ArrayList做例子)。

基本介绍

  1. List集合类中元素有序(即添加顺序和取出顺序一致)、且可重复。【案例A】
  2. List集合中的每个元素都有其对应的顺序索引,即支持索引。索引从0开始,【案例A】
  3. List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。
  4. JDK API中List接口的实现类有很多,常用的有: ArrayList、LinkedList和Vector。

【案例A】

    public static void main(String[] args) {
        //1) List集合类中元素有序(即添加顺序和取出顺序一致)、且可重复
        ArrayList list = new ArrayList();
        list.add("jack");
        list.add("mary");
        list.add("tom");
        list.add("tom");
        list.add("harry");
        System.out.println("list=" + list);
        //2) List集合中的每个元素都有其对应的顺序索引,即支持索引。
        System.out.println(list.get(0));
    }

常用方法

【案例B】

  1. void add(int index, Object ele):在index位置插入ele元素。没有设置index就默认插入到最后。
  2. boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
  3. Object get(int index):获取指定index位置的元素
  4. int indexOf(Object obj):返回obj在集合中首次出现的位置
  5. int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置
  6. Object remove(int index):移除指定index位置的元素,并返回此元素
  7. Object set(int index, Object ele):设置指定index位置的元素为ele , 相当于是替换。这个index必须 >=0,且<=list.length()-1
  8. List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
    注意返回的子集合 fromIndex <= subList < toIndex

【案例B】

    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("张三丰");
        list.add("贾宝玉");

//        void add(int index, Object ele):在index位置插入ele元素
        //在index = 1的位置插入一个对象
        list.add(1, "韩顺平");
        System.out.println("list=" + list);

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

//        Object get(int index):获取指定index位置的元素
        //说过

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

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

//        Object remove(int index):移除指定index位置的元素,并返回此元素
        list.remove(0);
        System.out.println("list=" + list);

//        Object set(int index, Object ele):设置指定index位置的元素为ele , 相当于是替换.
        list.set(1, "玛丽");
        System.out.println("list=" + list);

//        List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
        // 注意返回的子集合 fromIndex <= subList < toIndex
        List returnlist = list.subList(0, 2);
        System.out.println("returnlist=" + returnlist);

    }

List的三种遍历方式

[ArrayList, LinkedList, Vector]

  1. 方法一:使用 iterator
  2. 方法二:使用增强 for
  3. 方法三:使用普通 for
//使用普通 for
for(int i=0; i<list.size; i++) {
	Object obj = list.get(i);
	System.out.println(obj);
}

练习:实现冒泡排序

    //静态方法
    //价格要求是从小到大
    public static void sort(List list) {

        int listSize = list.size();
        for (int i = 0; i < listSize - 1; i++) {
            for (int j = 0; j < listSize - 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);
                }
            }
        }

    }
  • 21
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值