Java实现列表(Collection接口)

集合框架(集合的由来及集合继承体系图)

集合的由来:
面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,Java就提供了集合类。

数组和集合的区别

  1. 长度区别:数组的长度是固定的而集合的长度是可变的

  2. 存储数据类型的区别:数组可以存储基本数据类型 , 也可以存储引用数据类型; 而集合只能存储引用数据类型

  3. 内容区别:数组只能存储同种数据类型的元素 ,集合可以存储不同类型的元素

集合继承体系图:
在这里插入图片描述

package org.westos.demo;

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 14:15
 */
public class MyTest {
    public static void main(String[] args) {
        //需求:我有3个学生,请把这个3个学生的信息存储到数组中,并遍历数组,获取得到每一个学生信息。
        Student s1 = new Student("a", 30);
        Student s2 = new Student("b", 20);
        Student s3 = new Student("c", 30);
        //定义数组
        Student[] students = {s1, s2, s3, new Student("d", 34)};
        //Object[] objects = {"str", Integer.valueOf(10), 100};      
        //遍历输出
        for (int i = 0; i < students.length; i++) {
            Student student = students[i];
            System.out.println(student.getName() + "==" + student.getAge());
        }
    }
}
class Student {
        private String name;     //成员变量
        private int age;

    public Student() {
    }

    public Student(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          //之前说过,将Object类中的toString方法进行重写
    public String toString() {
         return "Student{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}

关于上面的一行代码 //Object[] objects = {"str", Integer.valueOf(10), 100}; ,虽然被注释掉了,但是还是要在这里讲解一下

  1. 为什么要引入列表,因为数组的长度不可变,而且数组只能存储一种数据类型的元素,但是列表却具有数组没有的一些优点,比如长度可变,可以存储多种数据类型的元素,这里可以直接调用ArrsyList类来创建一个列表,
  2. 但是也可以创建一个Object类的数组,因为Object类是所有类的顶层父类,所以该数组中可以存储多种数据类型的数据,但是在使用里面的元素时要注意要向下转型,而且它毕竟是数组,长度依然不能变
  3. 在这里插入图片描述通过上图可以看到,在调试的时候,object[1]Integer类型的,这没的说,因为使用了手动装箱,但是object[2]为什么也是Integer类型,因为使用到了自动装箱,也就是说在Object类的数字中,也是只能存储引用数据类型
  4. 那么如果我要定义一个列表,之中存放的是我自己自定义的一个类的数据类型,但是Java不知道我这个列表之中存放的是什么类,所以就将ArrayList所创建的列表中的所有对象定义为Object类,因为Object类是所有子类的顶层父类
  5. 但是使用ArrayList定义一个列表时会存在一个问题,不允许使用基本数据类型,只能用引用数据类型(数组、类、接口)也就是说如果我想在列表中存放int型无法实现,所以必须对基本数据类型进行包装,包装为Integer类型,也就是包装类(字符串String是个类)之后才能放进这个列表中中
  6. 也就是说从ArrayList定义的列表中取出的每一个元素都会被默认为使Object类,要使用列表中的元素时要注意向下转型

集合框架(Collection集合的功能概述)

Collection接口的功能概述(通过API查看即可得到)

  1. 添加功能:
  • boolean add(Object obj):添加一个元素,因为在这里Java不知道我想给列表中添加的内容是什么类型,所以就会将参数设置为Object

  • boolean addAll(Collection c):添加一个集合的元素 (给一个集合添加进另一个集合中的所有元素)

  1. 删除功能
  • void clear():移除所有元素

  • boolean remove(Object o):移除一个元素

  • boolean removeAll(Collection c):移除一个集合的元素(移除一个以上返回的就是true),移除的元素是两个集合的交集元素,如果没有交集元素 则删除失败 返回false

  1. 判断功能
  • boolean contains(Object o):判断集合中是否包含指定的元素

  • boolean containsAll(Collection c):判断集合中是否包含指定的集合元素(这个集合包含另一个集合中所有的元素才算包含,才返回true)

  • boolean isEmpty():判断集合是否为空

  1. 长度功能
    int size():元素的个数

  2. 交集功能
    boolean retainAll(Collection c):获取两个集合的交集元素(交集:两个集合都有的元素)

  3. 把集合转换为数组

    Object[] toArray()
    

集合框架(Collection集合的基本功能测试)

代码演示1:

package org.westos.java;

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

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 14:26
 */
public class MyTest {
    public static void main(String[] args) {
        //多态
        Collection collection = new ArrayList();
        //往容器中添加元素
        collection.add("a");
        collection.add("b");
        collection.add(1); 
        System.out.println(collection);
    }
}

在上述代码中,我们新建了一个列表,由于Collection是个接口,所以只能通过多态来实现实例化,即父类引用指向子类对象,在列表创建完成后,便可以调用对象中的方法,当然,这些方法都被子类进行了重写,这个列表中可以存储多种数据类型,collection.add(1); 这条语句给1进行了自动装箱
通过System.out.println(collection);来打印列表中的内容,程序运行结果为:

[a, b, 1]

代码演示2:

package org.westos.demo2;

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

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 14:36
 */
public class MyTest2 {
    public static void main(String[] args) {
        Collection collection=new ArrayList();
        collection.add(100);
        collection.add(Integer.valueOf(103));
        collection.add(100);
        collection.add(Integer.valueOf(104));
        collection.add(100);
        collection.add(Integer.valueOf(104));
        collection.add(100);
        collection.add(Integer.valueOf(1022));
        collection.add(100);
        collection.add(Integer.valueOf(103));


        Collection collection2 = new ArrayList();
        collection2.add(100);
        collection2.add(Integer.valueOf(103));
        collection2.add(100);
        collection2.add(Integer.valueOf(104));
        collection2.add(100);
        collection2.add(Integer.valueOf(104));
        collection2.add(100);
        collection2.add(Integer.valueOf(1022));
        collection2.add(100);
        collection2.add(Integer.valueOf(103));

        //A 集合去addAll(B集合) 把B集合的所有元素放到A集合里面去
        boolean b = collection.addAll(collection2);
        System.out.println(collection);
        System.out.println(collection2);


    }
}

这段代码调用了addAll方法,运行结果为:

[100, 103, 100, 104, 100, 104, 100, 1022, 100, 103, 100, 103, 100, 104, 100, 104, 100, 1022, 100, 103]
[100, 103, 100, 104, 100, 104, 100, 1022, 100, 103]

代码演示3:

package org.westos.java;

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

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 14:43
 */
public class MyTest {
    public static void main(String[] args) {
        //boolean removeAll (Collection c):移除一个集合的元素(移除一个以上返回的就是true) 删除的元素是两个集合的交集元素
        //如果没有交集元素 则删除失败 返回false

        Collection collection = new ArrayList();
        collection.add("123");
        collection.add("456");
        collection.add("789"); 
        collection.add("000");
        
        Collection collection2 = new ArrayList();
        collection2.add("123");
        collection2.add("456");
        collection2.add("7889"); 
        // A集合removeAll(B集合) A集合中,会删掉两个集合的交集元素,如果移除之后,A集合中发生变化返回true否则返回false
        boolean b = collection.removeAll(collection2);
        System.out.println(b);
        System.out.println(collection);
        System.out.println(collection2);
    }
}

代码运行结果为:

true
[789, 000]
[123, 456, 7889]

代码演示4:

package org.westos.java;

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

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 15:00
 */
public class MyTest {
    public static void main(String[] args) {
        //多态
        Collection collection2 = new ArrayList();
        //往容器中添加元素
        collection2.add("7889");
        collection2.add("123");
        collection2.add("555");
        //判断集合中是否存在该元素
        boolean b = collection2.contains("7889");
        boolean b1 = collection2.contains("11111");
        System.out.println(b);
        System.out.println(b1);
    }
}

上述代码运行结果为:

true
false

其他功能:

boolean addAll(Collection c)
boolean removeAll(Collection c)
boolean containsAll(Collection c)
boolean retainAll(Collection c)

和这些功能都比较类似,在这里不再讲解

集合框架(集合的遍历之集合转数组遍历)

集合的遍历:
toArray() 把一个集合转成数组,其实就是依次获取集合中的每一个元素。

把集合转成数组toArray(),遍历这个数组 可以实现集合的遍历

集合框架(Collection存储自定义对象并遍历)

如果要遍历列表,我们可以通过将列表转换为数组之后遍历数组,实现对列表的间接遍历
代码示例:

package org.westos.demo5;

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

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 15:29
 */
public class MyTest2 {
    public static void main(String[] args) {
        Collection collection = new ArrayList();      //定义一个新列表
        collection.add(10);
        collection.add(20);
        collection.add(30);
        collection.add(40);
        collection.add(60);
        collection.add(50);
        collection.add(60);
        //把集合转换成数组
        Integer[] integer=new Integer[collection.size()];   //确定数组的长度
        //遍历集合
        Iterator iterator = collection.iterator();
        int index=0;
        while (iterator.hasNext()){
            Object obj = iterator.next();
            Integer integer1= (Integer) obj;
            integer[index]=integer1;
                    index++;
		}
		System.out.println(Arrays.toString(integer));
    }
}

这是根据我们之前讲解的知识实现将列表转换为数组,先创建一个和列表等长的数组,之后获得列表的迭代器,在迭代的同时获取将每个元素并且向下转型,将转型后的Integer类的对象赋给数组对应位置上的元素,之后就会实现将列表转换为数组
但是也可以使用现成的方法:

Object[] objects = collection.toArray();
Object object = objects[0];
Integer integer = (Integer) object;
System.out.println(integer + 100);

在这段代码中直接使用了toArray方法,来实现将列表转换为数组,由于转换后的数组类型是Object类,所以在访问其中的每个元素时要注意向下转型,最后一句代码还使用到了自动拆箱

集合框架(集合的遍历之迭代器遍历)

迭代器概述: 对 collection 进行迭代的迭代器
该接口中的方法:

  • boolean hasNext(),如果仍有元素可以迭代,则返回 true
  • E next(),返回迭代的下一个元素。(这里E和泛型有关,后面会讲到)
  • void remove(),从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。

代码示例:

package org.westos.demo3;

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

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 15:07
 */
public class MyTest {
    public static void main(String[] args) {
        Collection collection1 = new ArrayList();
        //往容器中添加元素
        collection1.add("a");
        collection1.add("b");
        collection1.add("c"); 
        //获取一个迭代器
        //Iterator 对 collection 进行迭代的迭代器。
        //boolean hasNext ()
        //如果仍有元素可以迭代,则返回 true。
        //E next ()
        //返回迭代的下一个元素。

        Iterator iterator = collection1.iterator();
        System.out.println(iterator);

        while (iterator.hasNext()){
            Object obj = iterator.next();//让指针下移
            System.out.println(obj);  //在使用元素时最好进行向下转型
        }
    }
}

在上段代码中可以看到,使用到了迭代器IteratorIterator是个接口,通过多态来实现实例化

  1. 可以看到Iterator iterator = collection1.iterator();通过这段代码就可以获得该列表collection1的迭代器iterator

  2. 执行上段代码,System.out.println(iterator);的输出结果为:java.util.ArrayList$Itr @ 1540e19d,这是内部类编译过后的class文件名ArrayList$Itr,(内部类:可以直接访问外部类的成员,包括私有的)

  3. 如果我们使用文本而不使用环境来编写Java程序,那么如果在一个类中有内部类,在编译的时候就会编译生成两个class文件,一个是本类,一个是内部类

  4. 之后通过while循环迭代每一个元素

    while (iterator.hasNext()){
          Object obj = iterator.next();//让指针下移
          System.out.println(obj);
    }
    

代码便可以实现对列表中元素的遍历

代码示例2:

package org.westos.demo4;


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

/**
 * @Author: Administrator
 * @CreateTime: 2019-05-02 15:19
 */
public class MyTest {
    public static void main(String[] args) {
        Student s1 = new Student("1", 30);
        Student s2 = new Student("2", 20);
        Student s3 = new Student("3", 30);
        Collection collection=new ArrayList();
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        collection.add(new Student("4",24));
        //遍历
        Iterator iterator = collection.iterator();
       // iterator.next();//手动移动了一下指针
        while (iterator.hasNext()){
            Object obj = iterator.next();
            //向下转型
            Student student= (Student) obj;
            System.out.println(student.getName()+"==="+student.getAge());
        }  
    }
}
class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(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     //重写Object类中的toString方法
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在上述代码中自定义了Student类,,并且向列表中加入了3个Student类的对象,之后遍历列表,在遍历同时向下转型,打印每个对象的成员变量。比较容易理解

在这里顺带提一下:

int size = collection1.size();//获取集合的长度

size方法可以获取结合列表长度

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值