Java集合(上)

简介: Java集合(上)

一、集合框架的概述


1.集合、数组都是对多个数据进行存储操作的结构,简称Java容器。

  说明:此时的存储,主要指的是内存层面的存储,不涉及到持久化的存储(.txt,.jpg,.avi,数据中)


2.1  数组在存储多个数据方面的特点:

         >一旦初始化以后,其长度就确定了

         >数组一旦定义好,其元素的类型也都确定了。我们也就只能操作指定类型的数据了。

         比如:String[] arr,int[] arr1,Object[] arr2;

2.2  数组在存储多个数据方面的缺点:

         >一旦初始化以后,其长度就不可修改。

         >数组中提供的方法非常有限,对于添加、删除、插入数据等操作,非常不便,同时效率不高

         >获取数组中实际元素的个数的需求,数组没有现成的属性或方法可用

         >数组存储数据的特点:有序,可重复。对于无序,不可重复的需求,不能满足

3.集合框架

     |---Collection接口:单列集合,用来存储一个一个的对象

            |---List接口:存储有序的、可重复的数据      “动态数组”

                     |---ArraysList、LinkedList、Vector

            |---Set接口:存储无序的、不可重复的数据      “中学讲的”

                     |---HashSet、LinkedHashSet、TreeSet

     |---Map接口:双列集合,用来存储一对(key-value)一对的数据       “高中函数”:y = f(x)

                     |--HashMap、LinkedHashMap、TreeMap、Hashtable、Properties

图示如下:


b8884a0485a46a79dfe3328f5a74f1eb_520e3dd7f71349328e58bc19bd5cc2c3.png

819e7cfd6d583ea00755eb38b6039117_dcb9f6a3ec4e4dad9e34d91a9bf909f6.png


二、Collection接口及其方法


1、添加   add(Object obj)    addAll(Collection coll)


2、获取有效元素的个数 int size()


3、清空集合  void clear()


4、是否是空集合  boolean isEmpty()


5、是否包含某个元素 boolean contains(Object obj):是通过元素的equals方法来判断是否是同一个对象


boolean containsAll(Collection c):也是调用元素的equals方法来比较的。拿两个集合的元素挨个比较。


6、删除 boolean remove(Object obj) :通过元素的equals方法判断是否是 要删除的那个元素。只会删除找到的第一个元素


boolean removeAll(Collection coll):取当前集合的差集


7、取两个集合的交集  boolean retainAll(Collection c):把交集的结果存在当前集合中,不影响c 8、集合是否相等  boolean equals(Object obj)


9、转成对象数组  Object[] toArray()


10、获取集合对象的哈希值  hashCode()


11、遍历  iterator():返回迭代器对象,用于集合遍历


代码实现:


@Test
    public void test1(){
        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());//4
        //addAll(Collection coll1):将coll1集合中的元素添加到当前的集合中
        Collection coll1 = new ArrayList();
        coll1.add(456);
        coll1.add("CC");
        coll.addAll(coll1);
        System.out.println(coll.size());//6
        System.out.println(coll);
        //clear():清空集合元素
        coll.clear();
        //isEmpty():判断当前集合是否为空
        System.out.println(coll.isEmpty());
    }
/**
 * Collection接口中声明的方法的测试
 *
 * 结论:
 * 向Collection接口实现类的对象中添加数据obj时,要求obj所在类重写equals()
 *
 *
 * @author wyyyyyk
 * @create 2022-07-18 10:54
 */
public class CollectionTest {
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
//        Person p = new Person("Jerry",20);
//        coll.add(p);
        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(p));true
        System.out.println(coll.contains(new Person("Jerry",20)));//false-->true
        //2.containsAll(Collection coll1):判断形参coll1中的所有元素是否都存在于当前集合中
        Collection coll1 = Arrays.asList(123,4567);
        System.out.println(coll.containsAll(coll1));
    }
    @Test
    public void test2(){
        //3.remove(Object obj):从当前集合中移除obj元素
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        coll.remove(1234);
        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);
    }
    @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));
    }
    @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类的静态方法()
        List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);
        List arr1 = Arrays.asList(new int[]{123, 456});
        System.out.println(arr1);//1
        List arr2 = Arrays.asList(new Integer[]{123, 456});
        System.out.println(arr2.size());//2
        //9.iterator():返回Iterator接口的实例,用于遍历集合元素,放在IteratorTest.java中测试
    }
}


重要结论:向Collection接口实现类的对象中添加数据obj时,要求obj所在类重写equals()


三、Iterator迭代器接口


Iterator对象称为迭代器(设计模式的一种),主要用于遍历 Collection 集合中的元素。  GOF给迭代器模式的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。迭代器模式,就是为容器而生。类似于“公 交车上的售票员”、“火车上的乘务员”、“空姐”。  Collection接口继承了java.lang.Iterable接口,该接口有一个iterator()方法,那么所 有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了 Iterator接口的对象。  Iterator 仅用于遍历集合,Iterator 本身并不提供承装对象的能力。如果需要创建 Iterator 对象,则必须有一个被迭代的集合。  集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合 的第一个元素之前。


/**
 * //集合元素的遍历,使用迭代器Iterator接口
 *   1.内部的放啊:hashiNext() 和 next()
 *   2.集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。
 *   3.内部定义了remove(),可以在遍历的时候,删除集合中的元素,此方法不同于集合直接调用remove()
 *
 * @author wyyyyyk
 * @create 2022-07-19 14:06
 */
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());
        }
    }
    @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);
        //错误方式一:
//        Iterator iterator = coll.iterator();
//        while(iterator.next() != null){
//            System.out.println(iterator.next());
//        }
        //错误方式二:
        //集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合
        //的第一个元素之前。
        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()){
//            iterator.remove();
            Object obj = iterator.next();
            if("Tom".equals(obj)){
                iterator.remove();
//                iterator.remove();
            }
        }
        //重新遍历
        iterator = coll.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}


补充:使用 foreach 循环(增强for循环)遍历集合元素


Java 5.0 提供了 foreach 循环迭代访问 Collection和数组。  遍历操作不需获取Collection或数组的长度,无需使用索引访问元素。  遍历集合的底层调用Iterator完成操作。  foreach还可以用来遍历数组。


/**
 * jdk5.0新增foreach循环,用于遍历集合、数组
 *
 *
 * @author wyyyyyk
 * @create 2022-07-19 14:45
 */
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);
        }
    }
    @Test
    public void test2(){
        int[] arr = new int[] {1,2,3,4,5,6};
        //for(数组中元素的类型 局部变量   数组对象)
        for (int i : arr){
            System.out.println(i);
        }
    }
    @Test
    public void test3(){
        String[] arr = new String[]{"MM","MM","MM"};
        //方式一:普通for循环
//        for (int i = 0; i < arr.length; i++) {
            arr[i] = "GG";
        }
        //方式二:增强for循环
        for(String s : arr){
            s = "GG";
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}


四、Collection子接口之一: List接口及其实现类


鉴于Java中数组用来存储数据的局限性,我们通常使用List替代数组, List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。  List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据 序号存取容器中的元素。  JDK API中List接口的实现类常用的有:ArrayList、LinkedList和Vector。


/**
 *  1.List接口框架
 *   |---Collection接口:单列集合,用来存储一个一个的对象
 *  *             |---List接口:存储有序的、可重复的数据      “动态数组”
 *  *                      |---ArrayList:作为List接口的主要实现类,线程不安全的,效率高:底层使用Object[] elementData存储
 *                         |---LinkedList:对于频繁的插入、删除操作,使用此类效率比ArrayList高:底层使用双向链表存储
 *                         |---Vector:作为List接口的古老实现类,线程安全的,效率低:底层使用Object[]存储
 *
 *   2.ArrayList的源码分析:
 *      2.1jdk 7 情况下
 *          ArrayList list = new ArrayList();//底层创建了长度是10的Object[]数组elementData
 *          list.add(123);//elementData[0] = new Integer(123);
 *          ....
 *          list.add(11);//如果此次的添加导致底层elementData数组容量不够,则扩容
 *          默认情况下,扩容为原来的1.5倍,同时需要将原有数组中的数据复制到新的数组中
 *
 *          结论:建议开发使用带参的构造器:ArrayList list = new ArrayList(int copacity)
 *
 *      2.2jdk 8 中ArrayList的变化:
 *          ArrayList list = new ArrayList();//底层Object[] elementData初始化为{},并没有创建长度为10的数组
 *
 *          list.add(123);//第一次调用add()时,底层才创建了长度为10的数组,并将数据123添加到/elementData[0]
 *          ...
 *          后续的添加和扩容与jdk7无异
 *      2.3小结jdk7中ArrayList的创建类似于单例的饿汉式,而jdk8中的ArrayList的对象的
 *          创建类似于单例的懒汉式,延迟了数组的创建,节省内存
 *
 *   3.LinkedList的源码分析
 *      LinkedList list = new LinkedList();内部声明了Node类型的first和last属性,默认值为null
 *      list.add(123);//将123封装到Node中,创建了Node对象。
 *
 *      其中,Node定义为:体现了LinkedList的双向链表的说法
 *      private static class Node<E> {
 *         E item;
 *         Node<E> next;
 *         Node<E> prev;
 *
 *         Node(Node<E> prev, E element, Node<E> next) {
 *             this.item = element;
 *             this.next = next;
 *             this.prev = prev;
 *         }
 *     }
 *
 *   4.Vector的源码分析:jdk7和jdk8中通过Vector()构造器,底层斗创建了长度为10的数组
 *   在扩容方面,默认扩容为原来数组长度的2倍
 *
 *面试题:ArrayList、LinkList、Vector三者的异同?
 * 同:三个类都是实现了List接口,存储数据的特点相同:存储有序的、可重复的数据
 * 不同:见上
 *
 *   5.List接口的常用方法
 *
 *
 *
 * @author wyyyyyk
 * @create 2022-07-19 15:15
 */
public class ListTest {
    /*
    void add(int index, Object ele):在index位置插入ele元素
    boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
    Object get(int index):获取指定index位置的元素
    int indexOf(Object obj):返回obj在集合中首次出现的位置
    int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置
    Object remove(int index):移除指定index位置的元素,并返回此元素
    Object set(int index, Object ele):设置指定index位置的元素为ele
    List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
    总结:常用方法
    增:add(Object obj)
    删:remove(int index) / remove(Object obj)
    改:set(int index, Object ele)
    查:get(int index)
    插:add(int index, Object ele)
    长度:size()
    遍历:①Iterator迭代器方式
        ②增强for循环
        ③普通循环
     */
    @Test
    public void test3(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        //方式一:①Iterator迭代器方式
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("*************************");
        //方式二:②增强for循环0
        for (Object obj : list){
            System.out.println(obj);
        }
        System.out.println("*************************");
        //方式三:③普通循环
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
    @Test
    public void test2(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Tom",12));
        list.add(456);
        //int indexOf(Object obj):返回obj在集合中首次出现的位置,如果不存在返回-1
        int index = list.indexOf(4567);
        System.out.println(index);
        //int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置,如果不存在返回-1
        System.out.println(list.lastIndexOf(456));
        //Object remove(int index):移除指定index位置的元素,并返回此元素
        Object obj = list.remove(0);
        System.out.println(obj);
        System.out.println(list);
        //Object set(int index, Object ele):设置指定index位置的元素为ele
        list.set(1,"CC");
        System.out.println(list);
        //List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
        System.out.println(list.subList(2,4));
    }
    @Test
    public void test1(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Tom",12));
        list.add(456);
        System.out.println(list);
        //void add(int index, Object ele):在index位置插入ele元素
        list.add(1,"BB");
        System.out.println(list);
        //boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
        List list1 = Arrays.asList(1, 2, 3);
        list.addAll(list1);
        System.out.println(list.size());//9
        //Object get(int index):获取指定index位置的元素
        System.out.println(list.get(0));
    }
}


基于List接口的面试题:


面试题: 请问ArrayList/LinkedList/Vector的异同?谈谈你的理解?ArrayList底层 是什么?扩容机制?Vector和ArrayList的最大区别?


ArrayList和LinkedList的异同 二者都线程不安全,相对线程安全的Vector,执行效率高。 此外,ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。对于 随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针。对于新增和删除操作add(特指插入)和remove,LinkedList比较占优势,因为ArrayList要移动数据。  ArrayList和Vector的区别 Vector和ArrayList几乎是完全相同的,唯一的区别在于Vector是同步类(synchronized),属于 强同步类。因此开销就比ArrayList要大,访问要慢。正常情况下,大多数的Java程序员使用 ArrayList而不是Vector,因为同步完全可以由程序员自己来控制。Vector每次扩容请求其大 小的2倍空间,而ArrayList是1.5倍。Vector还有一个子类Stack。

目录
相关文章
|
17天前
|
安全 Java 大数据
|
15天前
|
安全 Java 开发者
【JAVA】哪些集合类是线程安全的
【JAVA】哪些集合类是线程安全的
|
15天前
|
Java
【JAVA】怎么确保一个集合不能被修改
【JAVA】怎么确保一个集合不能被修改
|
2天前
|
存储 安全 Java
Java一分钟之-集合框架进阶:Set接口与HashSet
【5月更文挑战第10天】本文介绍了Java集合框架中的`Set`接口和`HashSet`类。`Set`接口继承自`Collection`,特征是不允许重复元素,顺序不确定。`HashSet`是`Set`的实现,基于哈希表,提供快速添加、删除和查找操作,但无序且非线程安全。文章讨论了`HashSet`的特性、常见问题(如元素比较规则、非唯一性和线程安全性)以及如何避免这些问题,并提供了代码示例展示基本操作和自定义对象的使用。理解这些概念和注意事项能提升代码效率和可维护性。
9 0
|
2天前
|
存储 安全 算法
Java一分钟之-Java集合框架入门:List接口与ArrayList
【5月更文挑战第10天】本文介绍了Java集合框架中的`List`接口和`ArrayList`实现类。`List`是有序集合,支持元素重复并能按索引访问。核心方法包括添加、删除、获取和设置元素。`ArrayList`基于动态数组,提供高效随机访问和自动扩容,但非线程安全。文章讨论了三个常见问题:索引越界、遍历时修改集合和并发修改,并给出避免策略。通过示例代码展示了基本操作和安全遍历删除。理解并正确使用`List`和`ArrayList`能提升程序效率和稳定性。
7 0
|
4天前
|
存储 安全 算法
掌握Java并发编程:Lock、Condition与并发集合
掌握Java并发编程:Lock、Condition与并发集合
11 0
|
4天前
|
存储 安全 Java
深入理解Java集合框架
深入理解Java集合框架
9 0
|
9天前
|
存储 安全 Java
Java集合的分类有哪些?
Java中的集合就像一个容器,专门用来存储Java对象,这些对象可以是任意的数据类型,并且长度可变。这些集合类都位于java.util包中,在使用时一定要注意导包的问题,否则会出现异常。
36 10
|
12天前
|
安全 Java
循环的时候去删除集合中的元素 java.util.ConcurrentModificationException
循环的时候去删除集合中的元素 java.util.ConcurrentModificationException
|
14天前
|
Java
【专栏】Java 8 的 Streams 提供了一种处理数据集合的新方式,增强了代码的可读性和可维护性
【4月更文挑战第28天】Java 8 的 Streams 提供了一种处理数据集合的新方式,增强了代码的可读性和可维护性。本文介绍了 Streams 的基本概念,如从数据源创建 Stream,以及中间和终端操作。通过过滤、映射、归并、排序、分组等案例,展示了 Streams 的使用,包括并行 Streams 提高效率。学习 Streams 可以提升代码质量和效率,文章鼓励读者在实际开发中探索更多 Streams 功能。