Java | Collection接口

Collection接口

Person.java

import java.util.Objects;

/**
 * ClassName: Person
 * Date:      2020/3/3 14:01
 * author:    Oh_MyBug
 * version:   V1.0
 */
public class Person {
    private String name;
    private int agel;

    public Person() {
    }

    public Person(String name, int agel) {
        this.name = name;
        this.agel = agel;
    }

    public String getName() {
        return name;
    }

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

    public int getAgel() {
        return agel;
    }

    public void setAgel(int agel) {
        this.agel = agel;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", agel=" + agel +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        System.out.println("Person euals().....");
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return agel == person.agel &&
                Objects.equals(name, person.name);
    }

}

CollectionTest.java

import org.junit.Test;

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

/**
 * ClassName: CollectionTest
 * Date:      2020/3/3 13:03
 * author:    Oh_MyBug
 * version:   V1.0
 *
 * 一、集合框架的概述
 *  1. 集合、数组都是对多个数据进行存储操作的结构,简称Java容器。
 *     说明:此时的存储,主要指的是内存层面的存储,不涉及持久化的存储(.txt,.jpg,.avo,数据库中)
 *
 *  2.1 数组在存储多个数据方面的特点:
 *     > 一旦初始化以后,其长度就确定了。
 *     > 数组一旦定义好以后,其元素类型就也就确定了。
 *       我们也就只能操作指定类型的数据了。比如:String[] arr; int[] arr1; Object[] arr2;
 *  2.2 数组在存储多个数据方面的缺点:
 *     >  一旦初始化以后,其长度就不可修改。
 *     > 数组中提供的方法非常有限,对于添加、删除、插入数据等操作,非常不便,同时效率不高。
 *     > 获取数组中实际元素的个数的需求,数组没有现成的属性或方法可用
 *     > 数组存储数据的特点:有序、可重复。对于无序、不可重复的需求,不能满足。
 *
 * 二、集合框架
 *     |----Collection接口:单列集合,用来存储一个一个的对象
 *         |----List接口:存储有序的、可重复的数据     --> “动态”数组
 *              |----ArrayList、LinkedList、Vector
 *
 *         |----Set接口:存储无序的、不可重复的数据。  --> 高中讲的“集合”
 *              |----HashSet、LinkedHashSet、TreeSet
 *
 *     |----Map接口:双列集合,用来存储一对(key - value)一对的数据   --> 高中函数:y = f(x)
 *              |----HashMap、LinkedHashMap、TreeMap、Hashtable、Properties
 *
 * 三、Collection接口中的方法的使用
 */
public class CollectionTest {

    @Test
    public void test(){
        Collection coll = new ArrayList();

        // add(Object e):将元素e添加到集合coll中
        coll.add("AA");
        coll.add("BB");
        coll.add(123); // 自动装箱
        coll.add(new Date());

        // size():获取添加的元素的个数
        System.out.println(coll.size());

        // addAll():将coll1集合中的元素添加到当前的集合中
        Collection coll1 = new ArrayList();
        coll1.add(456);
        coll1.add("CC");
        coll.addAll(coll1);
        System.out.println(coll);

        // clear():清空集合元素
        coll.clear();

        // isEmpty():判断当前集合是否为空
        System.out.println(coll.isEmpty());

        /*
        输出:
            4
            [AA, BB, 123, Tue Mar 03 15:51:42 CST 2020, 456, CC]
            true
         */
    }
}

CollectionTest1.java

import org.junit.Test;

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

/**
 * ClassName: CollectionTest1
 * Date:      2020/3/3 13:58
 * author:    Oh_MyBug
 * version:   V1.0
 *
 * Collection接口中声明的方法的测试
 *
 * 向Colection接口的实现类的对象中添加数据obj时,要求obj所在类要重写equals()。
 *
 */
public class CollectionTest1 {

    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        // 1. contains(Object obj):判断当前集合中是否包含obj
        // 我们在判断是会调用obj对象所在类的equals()方法。
        boolean contains = coll.contains(123);
        System.out.println(contains);
        System.out.println(coll.contains(new String("Tom")));
        System.out.println(coll.contains(new Person("Jerry",20)));

        // 2. containsAll(Collection coll1):判断形参coll1中的所有元素是否存在于当前集合中
        Collection coll1 = Arrays.asList(123,456);
        System.out.println(coll.containsAll(coll1));

        /*
        输出:
            true
            true
            Person euals().....
            Person euals().....
            Person euals().....
            true
            true
         */
    }

    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        // 3. remove(Object obj):
        coll.remove(123);
        System.out.println(coll);

        coll.remove(new Person("Jerry",20));
        System.out.println(coll);

        // 4. removeAll(Collection coll1):差集,从当前集合中移除coll1中所有元素
        Collection coll1 = Arrays.asList(123,456);
        coll.removeAll(coll1);
        System.out.println(coll);

        /*
        输出:
            [456, Person{name='Jerry', agel=20}, Tom, false]
            Person euals().....
            Person euals().....
            [456, Tom, false]
            [Tom, false]
         */
    }

    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        // 5. retainAll(Collection coll1):交集,获取当前集合和coll1集合的交集,并返回当前集合
//        Collection coll1 = Arrays.asList(123,456,789);
//        coll.retainAll(coll1);
//        System.out.println(coll);

        // 6. equals(Object obj):要想返回true,需要当前集合和形参集合的元素都相同
        Collection coll1 = new ArrayList();
        coll1.add(123);
        coll1.add(456);
        coll1.add(new Person("Jerry",20));
        coll1.add(new String("Tom"));
        coll1.add(false);
        System.out.println(coll.equals(coll1));

        /*
        输出:
            Person euals().....
            true
         */
    }

    @Test
    public void test4(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        // 7. hashCode():返回当前对象的哈希值
        System.out.println(coll.hashCode());

        // 8. 集合 ----> 数组:toArray()
        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        // 拓展:数组 ----> 集合:调用Arrays类的静态方法asList()
        List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);

        List arr1 = Arrays.asList(123, 456);
        System.out.println(arr1);

        List<Integer> arr2 = Arrays.asList(new Integer[]{123, 456});
        System.out.println(arr2);

        /*
        输出:
            1583322579
            123
            456
            Person{name='Jerry', agel=20}
            Tom
            false
            [AA, BB, CC]
            [123, 456]
            [123, 456]
         */
    }
}

迭代器Iterator

IteratorTest.java

import org.junit.Test;

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

/**
 * ClassName: IteratorTest
 * Date:      2020/3/3 14:51
 * author:    Oh_MyBug
 * version:   V1.0
 *
 * 集合元素的遍历操作,使用迭代器Iterator接口
 * 1. 内部的方法:hasNext():判断是否还有下一个元素 和 Next():①指针下移 ②将下移以后集合位置上的元素返回
 * 2. 集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前
 * 3. 内部定义了remove(),可以在遍历的时候,删除集合中的元素。此方法不同于集合直接调用remove()
 */
public class IteratorTest {
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        Iterator iterator = coll.iterator();
        // 方式一:
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        // 报异常:NoSuchElementException
//        System.out.println(iterator.next());

        // 方式二:不推荐
//        for (int i = 0; i < coll.size(); i++) {
//            System.out.println(iterator.next());
//        }

        // 方式三:推荐
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        /*
        输出:
            123
            456
            Person{name='Jerry', agel=20}
            Tom
            false
         */
    }

    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        // 错误方式一:NoSuchElementException异常
        Iterator iterator = coll.iterator();
        while ((iterator.next()) != null){
            System.out.println(iterator.next());
        }

        // 错误方式二:死循环
//        while (coll.iterator().hasNext()){
//            System.out.println(coll.iterator().next());
//        }

    }

    // 测试iterator中的remove()
    // 如果还未调用next()或在上一次调用next方法之后调用了remove方法,
    // 在调用remove都会报IllegalStateException
    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        // 删除集合中“Tom”数据
        Iterator iterator = coll.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
//            iterator.remove();
            if ("Tom".equals(obj)){
                iterator.remove();
//                iterator.remove();
            }
        }

        // 遍历集合
        Iterator iterator1 = coll.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }

        /*
        输出:
            123
            456
            Person{name='Jerry', agel=20}
            false
         */
    }
}

foreach循环遍历集合或数组

ForTest.java

import org.junit.Test;

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

/**
 * ClassName: Fortest
 * Date:      2020/3/3 15:38
 * author:    Oh_MyBug
 * version:   V1.0
 *
 * jdk5.0 新增了foreach循环,用于遍历集合、数组
 */
public class ForTest {
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        // for(集合元素类型 局部变量:集合对象)
        // 内部仍然调用了迭代器
        for (Object obj: coll){
            System.out.println(obj);
        }

        /*
        输出:
            123
            456
            Person{name='Jerry', agel=20}
            Tom
            false
         */
    }

    @Test
    public void test2(){
        int[] arr = new int[]{1,2,3,4,5};

        // for(数组元素的类型 局部变量:数组对象)
        for (int i: arr) {
            System.out.println(i);
        }
        /*
        输出:
            1
            2
            3
            4
            5
         */
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值