JavaSE学习笔记 Java集合框架以及Collection集合的学习

Java集合框架以及Collection集合的学习

  • 前言(案例引入集合概念)
  • 1.集合的由来
  • 2.Java集合的框架
  • 3.Collection接口常见方法
    • 3.1 添加元素
    • 3.2 删除元素
    • 3.3 判断是否包含元素
    • 3.4 获取集合的长度
    • 3.5 获取集合的交集
    • 3.6 将集合转换为数组
  • 4.Collection集合的遍历
    • 4.1 foreach循环遍历
    • 4.2 Iterator迭代器遍历
  • 总结

前言(案例引入集合概念)

  • 案例演示:我有3个学生,请把这个学生的信息存储到数组中,并遍历数组,获得每一个学生信息。
    下面是给定学生类的具体信息:
学生:Student
成员变量:name,age
构造方法:无参构造,有参构造
成员方法:get()以及set()方法

数组实现学生信息的存储:

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


//测试类:
public class MyTest {
     
    public static void main(String[] args) {
     
        //存储三个学生信息,存储在数组中并进行遍历
        Student student1 = new Student("张三", 13);
        Student student2 = new Student("李四", 15);
        Student student3 = new Student("王五", 16);


        Student[] studentlist = new Student[3];
        studentlist[0]=student1;
        studentlist[1]=student2;
        studentlist[2]=student3;

        for (int i = 0; i < studentlist.length; i++) {
     
            System.out.println(studentlist[i]);

        }

    }
}

但是使用数组存储元素也会存在弊端:当数组中需要添加或者删除元素时,就比较麻烦,而集合概念的引入就解决这一问题。


1.集合的由来

  • 不管是哪一种数据结构,其实本质上就是容器,就是装对象的。因此我们需要搞清楚两点:(1)如何存储(2)存储特点。

前面我们学习过数组,我们先来看下数组是如何存储的以及数组的存储特点

  • 逻辑结构:线性的
  • 物理结构:顺序的存储结构
  • 申请内存:一次申请一大段连续的空间·,一旦申请到了,内存就固定了
  • 存储特点:所有数据存储在这个连续的空间中,数组中的每一个元素都是一个具体的数据(对象),所有数据都紧密排布,不能有间隔

JavaSE学习笔记 Java集合框架以及Collection集合的学习_第1张图片

关于数组的操作
查询:每一个元素都是一个数值下标,可以通过下标瞬间定位到某个元素
增加:1.先使用total变量辅助记录实际存储元素个数
2.从尾部增加:数组名【total++】=新元素
3.从其他位置插入:先把index位置开始所有元素后移,然后数组名【index】=新元素
删除:先把index后面的元素前移,然后数组名【total- -】=null
改:直接数组名【index】=新元素
数组的优点:按索引查询效率高
数组的缺点:添加/删除效率低

由于我们使用的是面向对象语言,所以,我们要经常使用对象。而很多时候,我们可能需要使用很的对象,这个时候,我们就只能使用以前讲过的数组进行存储了,而数组的特点是长度固定。这样的话就不适合变化的数据。所以,java重新提供了一种容器,用于存储对象,这种容器叫集合。

下面是数组与集合之间的区别:

数组和集合之间的区别
长度区别:数组的长度是固定的;集合的长度是可变
存储数据类型:数组可以存储基本数据类型,也可以存储引用数据类型;而集合只能存储引用数据类型
内容区别:数组只能存储同种数据类型的元素;集合可以存储不同类型的元素

2.Java集合的框架

为了满足用户数据更多种的逻辑关系,而设计一系列的不同于数组的聚合的抽象数据类型。这些接口和类在java.util包中,因为类型很丰富,因此我们通常称为集合框架。
JavaSE学习笔记 Java集合框架以及Collection集合的学习_第2张图片

JavaSE学习笔记 Java集合框架以及Collection集合的学习_第3张图片

Java集合类主要由两个根接口Collection和Map派生出来的,Collection派生出了三个子接口:List、Set、Queue(Java5新增的队列),因此Java集合大致也可分成List、Set、Queue、Map四种接口体系,(注意:Map不是Collection的子接口)。

其中List代表了有序可重复集合,可直接根据元素的索引来访问;Set代表无序不可重复集合,只能根据元素本身来访问;Queue是队列集合;Map代表的是存储key-value对的集合,可根据元素的key来访问value。

上图中淡绿色背景覆盖的是集合体系中常用的实现类,分别是ArrayList、LinkedList、HashSet、TreeSet、HashMap、TreeMap等实现类。


3.Collection接口常见方法

Collection接口中常见的方法如下,这些都是最基本常用的。
JavaSE学习笔记 Java集合框架以及Collection集合的学习_第4张图片


3.1 添加元素

Collection集合中添加元素的方法
add(Object obj) :添加元素对象到当前的集合中去
addAll(Collection other):添加other集合中的所有元素对象到当前集合中,即this = this ∪ other
import java.util.ArrayList;
import java.util.Collection;

public class MyTest {
     
    public static void main(String[] args) {
     
        Collection collection = new ArrayList();//Arraylist是Collection的子接口List的实现
        //add()往集合中添加元素,返回值的意思为该元素是否添加成功
        boolean flag = collection.add("aaa");
        System.out.println(flag);
        collection.add("bbb");
        collection.add("ccc");

        System.out.println(collection);
    }
}

public class MyTest2 {
     
    public static void main(String[] args) {
     
        Collection collection = new ArrayList();
        //集合中存储的元素为引用数据类型
        collection.add(10);//这里的数为Integer类型
        collection.add(20);
        collection.add(30);
        collection.add(5);
        collection.add(Integer.valueOf(25));
        collection.add(new Integer(60));

        System.out.println(collection);


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

public class MyTest2 {
     
    public static void main(String[] args) {
     
        Collection list = new ArrayList();
        //集合中的数据为引用数据类型
        list.add(1);//这里为Integer数据类型
        list.add(2);
        System.out.println(list);

        ArrayList list2 = new ArrayList();
        list2.add(1);
        list2.add(2);
        list2.add(3);
        list2.add(4);
        System.out.println(list2);


        list.addAll(list2);
        //list.add(list2);

        System.out.println("经过addAll方法后的list集合为:" + list);
        System.out.println("经过addAll方法后的list2集合为:" + list2);
    }


}

  • 这里需要注意的是:list.addAll(list2);与list.add(list2)方法的区别:

JavaSE学习笔记 Java集合框架以及Collection集合的学习_第5张图片


3.2 删除元素

Collection集合中删除元素的方法
void clear():移除所有元素
boolean remove(Object o):移除一个元素
boolean removeAll(Collection c):移除一个集合中的元素(移除一个以上返回的就是true)删除的元素是两个集合的交集元素。如果没有交集元素,则删除失败,返回false。
import java.util.ArrayList;
import java.util.Collection;

public class MyTest3 {
     
    public static void main(String[] args) {
     
        Collection collection = new ArrayList();
        collection.add("张三");
        collection.add("李四");
        collection.add("王五");
        System.out.println(collection);

        //boolean remove(Object o):移除一个元素
        collection.remove("王五");
        System.out.println("经过remove方法后:"+collection);

        //void clear():移除所有元素移除集合中所有的元素
        collection.clear();
        System.out.println(collection);

    }
}

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

public class MyTest4 {
     
    public static void main(String[] args) {
     
        Collection collection1 = new ArrayList();
        collection1.add(100);
        collection1.add(200);
        collection1.add(300);
        collection1.add(400);

        Collection collection2 = new ArrayList();
        collection2.add(1);
        collection2.add(2);
        collection2.add(100);
        collection2.add(200);

        //移除一个集合的元素(移除一个以上返回的就是true) 删除的元素是两个集合的交集元素
        boolean flag = collection1.removeAll(collection2);
        System.out.println(flag);
        System.out.println(collection1);
        System.out.println(collection2);
    }
}


3.3 判断是否包含元素

Colection集合是否包含元素
boolean isEmpty():判断当前集合是否为空集合
boolean contains(Object o):判断集合中是否包含指定的元素
boolean containsAll(Collection c):判断c集合中的元素是否在当前集合中都存在。即c集合是否是当前集合的“子集”。
import java.util.ArrayList;
import java.util.Collection;

public class MyTest5 {
     
    public static void main(String[] args) {
     
        Collection collection = new ArrayList();
        collection.add(100);
        collection.add("王五");
        collection.add(300);
        collection.add(200);

        //判断集合中是否包含该元素,如果包含元素返回true
        boolean flag = collection.contains(100);
        System.out.println(flag);
        System.out.println(collection);
    }
}

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

public class MyTest6 {
     
    public static void main(String[] args) {
     
        Collection collection1=new ArrayList();
        collection1.add(100);
        collection1.add(200);
        collection1.add(300);
        collection1.add(400);
        collection1.add(500);


        Collection collection2 = new ArrayList();
        collection2.add(100);
        collection2.add(200);

         /* 判断集合中是否包含指定的集合元素(这个集合 包含 另一个集合中所有的元素才算包含 才返回true)
           比如:[1,2,3]containsAll [1,2] = true, [1, 2, 3]containsAll[2, 3, 4]= false*/
        boolean flag = collection1.containsAll(collection2);
        System.out.println(flag);
        System.out.println(collection1);
        System.out.println(collection2);


        collection2.clear();
        //boolean isEmpty():判断当前集合是否为空集合
        boolean b = collection2.isEmpty();
        System.out.println(b);
    }
}

3.4 获取集合的长度

  • 我们知道数组和字符串中有length()方法可以获得其长度,但集合中没有length()方法,那我们如何获取集合的长度呢?
Collection集合为获取集合的长度的方法
int size():元素的个数
import java.util.ArrayList;
import java.util.Collection;

public class MyTest7 {
     
    public static void main(String[] args) {
     
        Collection collection = new ArrayList();
        collection.add(100);
        collection.add(200);
        collection.add(300);
        collection.add(400);

        //获取集合长度的方法
        int size = collection.size();
        System.out.println(size);
    }
}


3.5 获取集合的交集

  • 集合的交集功能实质性解析:A集合对B集合取交集,获取到的交集元素在A集合中。返回的布尔值是A集合是否发生变化。A集合对B集合取交集元素,如果没有取到交集元素,A集合会被清空。
Collection集合获取两个集合交集
boolean retainAll(Collection c):获取两个集合的交集元素(交集:两个集合都有的元素)
import java.util.ArrayList;
import java.util.Collection;

public class MyTest8 {
     
    public static void main(String[] args) {
     
        Collection collection1 = new ArrayList();
        collection1.add(10);
        collection1.add(20);
        collection1.add(30);
        collection1.add(200);


        Collection collection2 = new ArrayList();
        collection2.add(10);
        collection2.add(20);
        collection2.add(300);
        collection2.add(400);

       // boolean retainAll(Collection c):获取两个集合的交集元素(交集:两个集合都有的元素)
        /*
        例如:A集合对B集合取交集,获取到的交集元素在A集合中。返回的布尔值表示的是A集合是否发生变化
			 A集合对B集合取交集元素,如果没有取到交集元素A集合会被清空
         */
        boolean flag = collection1.retainAll(collection2);
        System.out.println(flag);
        System.out.println(collection1);
        System.out.println(collection2);


    }
}

3.6 将集合转换为数组

Collection集合将集合转换为数组
Object[] toArray():返回包含当前集合中所有元素的数组
public class MyTest9 {
     
    public static void main(String[] args) {
     
        Collection collection=new ArrayList();
        collection.add(100);
        collection.add(200);
        collection.add(300);
        collection.add(400);

        //将集合转换为数组
        Object[] objects = collection.toArray();
        //遍历数组
        for (int i = 0; i < objects.length; i++) {
     
            System.out.println(objects[i]);

        }

    }
}

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

public class MyTest {
     
    public static void main(String[] args) {
     
        Student s1 = new Student("张三", 23);
        Student s2 = new Student("李四", 24);
        Student s3 = new Student("王五", 25);

      Collection collection=new ArrayList();
      collection.add(s1);
      collection.add(s2);
      collection.add(s3);

//将集合转换为数组
        Object[] objects = collection.toArray();
        for (int i = 0; i < objects.length; i++) {
     
            Student stu= (Student) objects[i];
            System.out.println(stu);
        }
    }
}




4.Collection集合的遍历

Collectio集合中有两种常见的遍历的方式:foreach循环遍历以及Iterator迭代器遍历。

4.1 foreach循环遍历

Java5以后Collection接口中继承了java.lang.Iterable接口,因此Collection系列集合就可以直接使用foreach循环来进行遍历。

foreach循环遍历格式:for(元素的类型 迭代变量: 数组/集合名称){
//每一个循环迭代变量依次代表集合中的每一个元素

JavaSE学习笔记 Java集合框架以及Collection集合的学习_第6张图片

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);
        //增强for循环
        for (Object o : collection) {
     
            System.out.println(o);
            //collection.add(5);  //错误
            //collection.remove(10); //错误
            /*
             foreach循环只适用于查看/查找集合中的元素,不能在
             遍历集合时,有任何影响集合元素个数的操作,否则会
             报异常或者操作结果不确定
             */

        }
    }
}

  • 在这里需要注意的是:foreach遍历只适用于查看/查找集合中的元素,不能在遍历集合时有任何影响集合元素个数的操作,否则会报异常或者操作结果不确定

提示:集合中只能添加对象,不能添加基本数据类型的数据,如果添加基本数据类型的数据,它会自动装箱为对应包装类型的对象。


4.2 Iterator迭代器遍历

因为Collection接口继承了java.lang.Iterable接口,该接口中有iterator()方法,那么所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象,该对象可以迭代集合中的元素

  • Iterator仅用于遍历集合,Iterator本身并不提供承装对象的能力。如果需要Iterator对象,就必须有一个被迭代的集合
  • 集合对象每次调用iterator()方法都能得到一个全新的迭代器对象,默认游标都在集合的第一个元素。

JavaSE学习笔记 Java集合框架以及Collection集合的学习_第7张图片

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

public class MyTest2 {
     
    public static void main(String[] args) {
     
        //使用迭代器遍历Collection集合
        //java.util 接口 Iterator
        //java.util.ArrayList$Itr @ 1 b6d3586
        //迭代器是内部类,内部类直接可以访问外部类的成员
        // private class Itr implements Iterator
      /*  方法摘要
        boolean hasNext ()
        如果仍有元素可以迭代,则返回 true。
        E next ()
        返回迭代的下一个元素。*/
        //
        Collection collection = new ArrayList();
        collection.add(10);
        collection.add(20);
        collection.add(30);
        collection.add(40);
        collection.add(50);


        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
     
            Object next = iterator.next();
            System.out.println(next);

        }
    }
}

        
public class Student {
     
    private int id;
    private String name;

    public Student() {
     
    }

    public Student(int id, String name) {
     
        this.id = id;
        this.name = name;
    }

    public int getId() {
     
        return id;
    }

    public void setId(int id) {
     
        this.id = id;
    }

    public String getName() {
     
        return name;
    }

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

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

public class MyTest {
     
    public static void main(String[] args) {
     
        Collection collection = new ArrayList();
        Student s1 = new Student(1, "张三");
        Student s2 = new Student(2, "李四");
        Student s3 = new Student(3, "王五");

        collection.add(s1);
        collection.add(s2);
        collection.add(s3);

        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
     
            //向下转型
          Student student= (Student) iterator.next();
            System.out.println(student);

        }

    }
}

总结

本节首先对集合的引入进行介绍,比较集合与数组之间的区别。总体探讨了下Java集合框架图,对于后面的集合具体学习明确了方向。最后,对于Collection集合中的常用方法以及遍历方式进行介绍。希望此篇文章对于正在学习集合的朋友有所帮助。
JavaSE学习笔记 Java集合框架以及Collection集合的学习_第8张图片

你可能感兴趣的:(JAVASE,集合,java,编程语言,集合)