Collection集合

Collection集合,第1张

Collection集合
  • 1、集合框架集
  • 2、Collection集合
    • 2.1 Collection集合的方法
    • 2.2 案例:增加和删除元素
    • 2.3 foreach循环遍历
    • 2.4 Iterator迭代器遍历

1、集合框架集

  集合框架集大致分为两大系列:一个是Collection系列,另一个是Map系列。

  Collection结合框架中的接口和类主要是用于存储和 *** 作一个一个的对象,称为单列集合。java.util.Collection是该系列中的根接口,提供了一些列方法供继承或实现。JDK不提供此接口的任何直接实现,而是提供了更具体的子接口(如Set和List、Queue)的实现。

  • List:有序的Collection(也称序列)。此接口的用户可以对列表中每个元素的插入位置进行精确控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。
  • Queue:队列通常以FIFO(先进先出)的方式排序各个元素。不过优先级队列和LIFO队列(或堆栈)除外,前者根据系统提供的比较器或元素的自然顺序对元素进行排序,后者按LIFO(后进先出)的方式对元素进行排序。
  • Set:一个不包含重复元素的Collection。更确切地讲,Set不包含满足eq.equals(e2)结果为true地元素对象e1和e2,并且最多包含一个null元素。

  Map集合框架中地接口和类主要用于存储和 *** 作由键映射到值得键值对(key、value)。java.util.Map是根接口,一个Map中不能包含重复得键,每个键最多只能映射到一个值。那如果一个键想要映射到多个值怎么办?那就把多个值放到一个Collection容器或数组中,然后统一由一个key映射。

  Map接口提供三种Collection视图,允许以键集、值集或键-值映射关系集得形式查看某个映射得内容。一些映射实现可明确保证其顺序,如TreeMap类;另一些映射实现则不保证其顺序,如HashMap类。SortedMap进一步提供关于键得总体排序的Map,该映射是根据键的自然顺序进行排序的,或者根据通常在创建有序映射时提供的Comparator排序。

2、Collection集合 2.1 Collection集合的方法

  (1)添加元素

  • add(Object obj):添加一个元素对象到当前集合中。
  • addAll(Collection other):添加other集合中的所有元素对象到当前集合中,当前集合相当于成了它们的并集,即 t h i s = t h i s ∪ o t h e r this=this\cup other this=thisother

  (2)删除元素

  • boolean remove(Object obj):从当前集合中删除第一个找到的与obj对象相等的元素,比较非空对象是否相等依赖于元素的equals方法。
  • boolean removeAll(Collection coll):从当前集合中删除所有与coll集合中元素相等的元素,相当于从当前集合中删除它们的交集,即 t h i s = t h i s − t h i s ∩ o t h e r this=this-this\cap other this=thisthisother,其中this代表调用removeAll方法的当前集合。
  • boolean retainAll(Collection coll):当前集合仅保留与coll集合中元素相等的元素,相当于当前集合中仅保留两个集合的交集,即 t h i s = t h i s ∩ c o l l this=this\cap coll this=thiscoll

  (3)判断元素

  • boolean isEmpty():判断当前集合是否为空集合。
  • boolean contains(Object obj):判断当前集合中是否存在一个与obj对象相等的元素。
  • boolean containsAll(Collection c):判断c集合中的元素是否在当前集合中都存在,即c集合是否是当前集合的子集。

  (4)查看

  • int size():获取当前集合中世纪存储的元素个数。
  • Object[] toArray():返回包含当前集合中所有元素的数组。
  • Iterator iterator():返回遍历当前集合元素的迭代器。
2.2 案例:增加和删除元素

  一个一个添加元素的示例代码:

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

public class CollectionAddTest {
    public static void main(String[] args) {
       Collection coll = new ArrayList();//ArrayList是Collection的子接口List的实现类
        coll.add("张三");
        coll.add("李四");
        coll.add("王五");
        coll.add("张三");
        System.out.println("coll集合元素的个数:"+coll.size());
    }
}

  一次添加多个元素的示例代码:

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

public class CollectionAndAllTest {
    public static void main(String[] args) {
        Collection coll = new ArrayList();//ArrayList是Collection的子接口List的实现类
        coll.add(1);
        coll.add(2);
        System.out.println("coll集合元素的个数:"+coll.size());

        Collection other=new ArrayList();
        other.add(1);
        other.add(2);
        other.add(3);

        coll.addAll(other);
        System.out.println("coll集合元素的个数:"+coll.size());
    }
}

  删除一个元素的示例代码:

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

public class CollectionRemoveTest {
    public static void main(String[] args) {
        Collection coll=new ArrayList();
        coll.add("张三");
        coll.add("李四");
        coll.add("王五");
        coll.add("张三");
        System.out.println("coll集合的元素个数:"+coll.size());
        coll.remove("张三"); //删除一个元素
        System.out.println("coll集合的元素个数:"+coll.size());
    }
}

  删除多个元素的示例代码,如删除两个集合的交集。

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

/**
 * 删除多个元素
 */
public class CollectionRemoveAllTest {
    public static void main(String[] args) {
        Collection coll=new ArrayList();
        coll.add(1);//自动装箱为包装类对象
        coll.add(2);
        coll.add(3);
        coll.add(4);
        coll.add(5);
        System.out.println("coll集合元素的个数:"+coll.size());//5

        Collection other=new ArrayList();
        other.add(1);
        other.add(2);
        other.add(8);
        coll.removeAll(other);//从coll中删除与other集合的所有交集元素
        System.out.println("coll集合元素的个数:"+coll.size());//3
    }
}

  删除多个元素的示例代码,如保留两个集合的交集。

public class CollectionRetainAllTest {
    public static void main(String[] args) {
        Collection coll=new ArrayList();
        coll.add(1);//自动装箱为包装类对象
        coll.add(2);
        coll.add(3);
        coll.add(4);
        coll.add(5);
        System.out.println("coll集合元素的个数:"+coll.size());//5
        for (Object o : coll) {
            System.out.println(o);
        }

        Collection other=new ArrayList();
        other.add(1);
        other.add(2);
        other.add(8);
        coll.retainAll(other);//仅在coll中保留coll与other集合的交集元素
        System.out.println("coll集合元素的个数:"+coll.size());//2
        for (Object o : coll) {
            System.out.println(o);
        }
    }
}

2.3 foreach循环遍历

  Java5java.lang包增加了一个Iterator接口,实现这个接口允许对象称为foreach语句的目标。同时Java5让Colletcion接口继承了Iterator接口,因此Collection系列的集合就可以直接使用foreach(循环遍历)。

语法格式如下:

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

  java5之后,所有数组默认都支持foreach循环遍历,而对于集合来说,只有实现了Iterator接口的集合才能使用foreach循环遍历。

  使用foreach循环遍历Collection集合的示例代码:

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

public class CollectionForeachTest {
    public static void main(String[] args) {
       Collection coll = new ArrayList<>();
       coll.add(1);
       coll.add(2);
       coll.add(3);
       coll.add(4);

       //foreach循环4次,obj每一次代表一个元素
        for (Object o : coll) {
            System.out.println(o);
        }
    }
}

   foreach蓄奴韩遍历只适用于查看/查找集合中的元素,不能在遍历集合时有任何影响集合元素个数的 *** 作,否则会报异常或 *** 作结果将不确定。

2.4 Iterator迭代器遍历

  因为Collection接口继承了java.lang.Iterable接口,那么Collection系列中所有的集合类也都具备了iterator()方法,用以返回一个java.util.Iterator接口的实现类对象,该对象用于迭代集合中的元素。其实上面的foreach循环底层也是调用Iterator迭代器的方法实现遍历过程的。

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

  Iterator迭代器的常用方法如下:

  • boolean hasNext():如果仍有元素可以迭代,则返回true。
  • Object next():返回迭代的下一个元素。在调用it.next()方法之前必须要调用it.hasNext()进行检测。若不调用,且下一条记录无效,则直接调用it.next()会抛出NoSuchElementException
  • void remove():从迭代器指向的Collection中移除迭代器返回的最后一个元素。如果还未调用next方法或在上一次调用next方法之后已经调用了remove方法,那么再调用就会报IllegalStateException

  使用Iterator迭代器遍历Collection集合的示例代码:

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

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

    public int getId() {
        return Id;
    }

    public void setId(int id) {
        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 + '\'' +
                '}';
    }
}

  测试类代码:

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

/**
 * Iterator迭代器遍历
 */
public class CollectionIteratorTest {
    public static void main(String[] args) {
        Collection c=new ArrayList();
        c.add(new Student(1,"张三"));
        c.add(new Student(2,"李四"));
        c.add(new Student(3,"王五"));
        c.add(new Student(4,"赵六"));
        c.add(new Student(5,"钱七"));

        Iterator iterator = c.iterator();
        while (iterator.hasNext()){
            Student next = (Student) iterator.next();
            //例如:要删除学号为1的学生对象
            if(next.getId()==1){
                iterator.remove();
            }
        }
        for (Object o : c) {
            System.out.println(o);
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/3002743.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-27
下一篇 2022-09-27

发表评论

登录后才能评论

评论列表(0条)

保存