Interface definition of collection class List

Posted by dcace on Sat, 30 Nov 2019 21:17:37 +0100

Collection class

Objectives:
Let's see what collection classes are included in JAVA first?
First, let's take a look at some classes related to List, and find out what implementation classes they have and what the usage scenarios of these implementation classes are.

Class diagram

This is a class diagram. We see that all collection classes are implemented

  1. Iterable
  2. Collection
  3. List

Let's first look at what they have implemented and explore how they have implemented it.

Iterable

Iterators, mainly providing iterators, parallel iterators and defining all collection classes to support forEach methods. Things like forEach and parallel iterators are new in jdk8. I'll learn something new in jdk8.

Collection collection

The difference between toArray() and < T > t [] toArray (t [] a)

  1. toArray() can only return Object [] and cannot cast (String[]) strings.toArray(). Error will be reported
  2. toArray(T[] a) will not have this problem

containsAll method

    @Test
    public void testContainsAll() {
        List<String> lists = new ArrayList<>();
        lists.add("1");
        lists.add("2");
        lists.add("3");

        System.out.println("============>" + lists.contains("1"));

        List<String> lists1 = new ArrayList<>();

        System.out.println("============>" + lists.containsAll(lists1));

        lists1.add("1");

        System.out.println("============>" + lists.containsAll(lists1));

        lists1.add("4");

        System.out.println("============>" + lists.containsAll(lists1));
    }

=========Result=========
============>true
============>true
============>true
============>false

retainAll Union

    @Test
    public void testRetainAll() {
        List<String> lists = new ArrayList<>();
        lists.add("1");
        lists.add("2");
        lists.add("3");
        lists.retainAll(new ArrayList<>());
        System.out.println("============>" + lists);


        lists.add("1");
        lists.add("2");
        lists.add("3");

        List<String> lists1 = new ArrayList<>();
        lists1.add("1");
        lists1.add("a");
        lists.retainAll(lists1);
        System.out.println("============>" + lists);
    }
-------------------
============>[]
============>[1]

List interface

Take a look at what methods are available for this interface compared with Collection?

Sort sort method

    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

add get set method subList method

Topics: Java