Java zero-based learning 028-API advanced ninth day

API-day09

collection (continued)

Operations between collections

Sets provide operations such as taking unions, deleting intersections, and judging the inclusion of subsets.

package collection;

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

/**
 * 集合间的操作
 */
public class CollectionDemo4 {
    
    
    public static void main(String[] args) {
    
    
//        Collection c1 = new ArrayList();
        Collection c1 = new HashSet();//不可重复元素
        c1.add("java");
        c1.add("c");
        c1.add("c++");
        System.out.println("c1:"+c1);
        Collection c2 = new ArrayList();
        c2.add("android");
        c2.add("ios");
        c2.add("java");
        System.out.println("c2:"+c2);
         /*
            boolean addAll(Collection c)
            将给定集合中的所有元素添加到当前集合中。当前集合若发生了改变则返回true
         */
        boolean tf = c1.addAll(c2);
        System.out.println(tf);
        System.out.println("c1:"+c1);
        System.out.println("c2:"+c2);

        Collection c3 = new ArrayList();
        c3.add("ios");
        c3.add("c++");
        c3.add("php");
        System.out.println("c3:"+c3);
        /*
            boolean containsAll(Collection c)
            判断当前集合是否包含给定集合中的所有元素
         */
        boolean contains = c1.containsAll(c3);
        System.out.println("包含所有元素:"+contains);

        /*
            boolean removeAll(Collection c)
            删除当前集合中与给定集合中的共有元素
         */
        c1.removeAll(c3);
        System.out.println("c1:"+c1);
        System.out.println("c3:"+c3);
    }
}

collection traversal

Collection provides a unified way to traverse collections: iterator mode

Iterator iterator()

This method gets an iterator for traversing the elements of the current collection.

java.util.Iterator interface

Iterator interface defines related operations for iterators to traverse collections.

Different collections implement an iterator implementation class for traversing their own elements. We don't need to remember their names, and we can regard them as Iterators from a polymorphic perspective.

The steps followed by the iterator to traverse the collection are: ask, fetch, delete. Deleting elements is not a necessary operation

package collection;

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

/**
 * Collection接口没有定义单独获取某一个元素的操作,因为不通用。
 * 但是Collection提供了遍历集合元素的操作。该操作是一个通用操作,无论什么类型的
 * 集合都支持此种遍历方式:迭代器模式。
 *
 * Iterator iterator()           die(二声)
 * 该方法会获取一个用于遍历当前集合元素的迭代器
 *
 * java.util.Iterator接口,是迭代器接口,规定了迭代器遍历集合的相关操作,不同的
 * 集合都提供了一个用于遍历自身元素的迭代器实现类,不过我们不需要直到它们的名字,以
 * 多态的方式当成Iterator使用即可。
 * 迭代器遍历集合遵循的步骤为:问->取->删
 * 其中删除不是必须操作。
 *
 */
public class IteratorDemo {
    
    
    public static void main(String[] args) {
    
    
        Collection c = new ArrayList();
        c.add("one");
        c.add("two");
        c.add("three");
        c.add("four");
        c.add("five");
        System.out.println(c);
        //获取迭代器
        Iterator it = c.iterator();
        /*
            迭代器提供的相关方法:
            boolean hasNext()
            判断集合是否还有元素可以遍历

            E next()
            获取集合下一个元素(第一次调用时就是获取第一个元素,以此类推)
         */
        while(it.hasNext()){
    
    
            String str = (String)it.next();
            System.out.println(str);         
        }
        System.out.println(c);

    }
}

During the traversal of the iterator, elements cannot be added or deleted through the collection method

package collection;

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

/**
 * Collection接口没有定义单独获取某一个元素的操作,因为不通用。
 * 但是Collection提供了遍历集合元素的操作。该操作是一个通用操作,无论什么类型的
 * 集合都支持此种遍历方式:迭代器模式。
 *
 * Iterator iterator()           die(二声)
 * 该方法会获取一个用于遍历当前集合元素的迭代器
 *
 * java.util.Iterator接口,是迭代器接口,规定了迭代器遍历集合的相关操作,不同的
 * 集合都提供了一个用于遍历自身元素的迭代器实现类,不过我们不需要直到它们的名字,以
 * 多态的方式当成Iterator使用即可。
 * 迭代器遍历集合遵循的步骤为:问->取->删
 * 其中删除不是必须操作。
 *
 */
public class IteratorDemo {
    
    
    public static void main(String[] args) {
    
    
        Collection c = new ArrayList();
        c.add("one");
        c.add("#");
        c.add("two");
        c.add("#");
        c.add("three");
        c.add("#");
        c.add("four");
        c.add("#");
        c.add("five");
        System.out.println(c);
        //获取迭代器
        Iterator it = c.iterator();
        /*
            迭代器提供的相关方法:
            boolean hasNext()
            判断集合是否还有元素可以遍历

            E next()
            获取集合下一个元素(第一次调用时就是获取第一个元素,以此类推)
         */
        while(it.hasNext()){
    
    
            String str = (String)it.next();
            System.out.println(str);
            if("#".equals(str)){
    
    
                /*
                    迭代器要求遍历的过程中不得通过集合的方法增删元素
                    否则会抛出异常:ConcurrentModificationException
                 */
//                c.remove(str);
                /*
                    迭代器的remove方法可以将通过next方法获取的元素从集合
                    中删除。
                 */
                it.remove();
            }
        }
        System.out.println(c);

    }
}

Enhanced for loop

A feature was introduced after JDK5: enhanced for loop

  • Also known as a new loop, allows us to iterate over collections or arrays using the same syntax.
  • grammar:
for(元素类型 变量名 : 集合或数组){
    循环体
}
package collection;

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

/**
 * JDK5推出时,推出了一个新的特性:增强型for循环
 * 也称为新循环,它可以用相同的语法遍历集合或数组。
 *
 * 新循环是java编译器认可的,并非虚拟机。
 */
public class NewForDemo {
    public static void main(String[] args) {
        String[] array = {"one","two","three","four","five"};
        for(int i=0;i<array.length;i++){
            String str = array[i];
            System.out.println(str);
        }

        for(String str : array){
            System.out.println(str);
        }


        Collection c = new ArrayList();
        c.add("one");
        c.add("two");
        c.add("three");
        c.add("four");
        c.add("five");
        //迭代器遍历
        Iterator it = c.iterator();
        while(it.hasNext()){
            String str = (String)it.next();
            System.out.println(str);
        }
        //新循环遍历
        for(Object o : c){
            String str = (String)o;
            System.out.println(str);
        }

    }
}

generic

Another feature introduced after JDK5: generics

Generics, also known as parameterized types, allow us to specify the types of properties, method parameters, or return values ​​in a class when we use it.

  • Generics are widely used in collections to specify the type of elements in the collection.
  • If a class with generic support is used without specifying the specific type of the generic, it defaults to the prototype Object
package collection;

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

/**
 * JDK5推出时,推出了一个新的特性:增强型for循环
 * 也称为新循环,它可以用相同的语法遍历集合或数组。
 *
 * 新循环是java编译器认可的,并非虚拟机。
 */
public class NewForDemo {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "one","two","three","four","five"};
        for(int i=0;i<array.length;i++){
    
    
            String str = array[i];
            System.out.println(str);
        }

        for(String str : array){
    
    
            System.out.println(str);
        }

        /*
         *  泛型 JDK5之后推出的另一个特性。
         * 泛型也称为参数化类型,允许我们在使用一个类时指定它里面属性的类型,
         * 方法参数或返回值的类型,使得我们使用一个类时可以更灵活。
         * 泛型被广泛应用于集合中,用来指定集合中的元素类型。
         * 支持泛型的类在使用时如果未指定泛型,那么默认就是原型Object
         *
         * Collection接口的定义
         * public interface Collection<E> ... {
         *
         * Collection<E> 这里的<E>就是泛型
         *
         * Collection中add方法的定义,参数为E
         * boolean add(E e)
         */
        Collection<String> c = new ArrayList<>();
        c.add("one");//编译器会检查add方法的实参是否为String类型
        c.add("two");
        c.add("three");
        c.add("four");
        c.add("five");
//        c.add(123);//编译不通过
        //迭代器遍历
        //迭代器也支持泛型,指定的与其遍历的集合指定的泛型一致即可
        Iterator<String> it = c.iterator();
        while(it.hasNext()){
    
    
            //编译器编译代码时会根据迭代器指定的泛型补充造型代码
            String str = it.next();//获取元素时无需在造型
            System.out.println(str);
        }
        //新循环遍历
        for(String str : c){
    
    
            System.out.println(str);
        }

    }
}

List set

java.util.List interface, inherited from Collection.

The List collection is a repeatable set and ordered, providing a set of methods for manipulating elements through subscripts

Common implementation classes:

  • java.util.ArrayList: Internally implemented using arrays, the query performance is better.
  • java.util.LinkedList: Internally implemented using a linked list, the performance of adding and deleting elements at the beginning and end is better.

Common methods of List collection

get() and set()

package collection;

import java.util.ArrayList;
import java.util.List;

/**
 *  List集合
 *  List是Collection下面常见的一类集合。
 *  java.util.List接口是所有List的接口,它继承自Collection。
 *  常见的实现类:
 *  java.util.ArrayList:内部由数组实现,查询性能更好。
 *  java.util.LinkedList:内部由链表实现,增删性能更好。
 *
 *  List集合的特点是:可以存放重复元素,并且有序。其提供了一套可以通过下标
 *  操作元素的方法。
 */
public class ListDemo {
    
    
    public static void main(String[] args) {
    
    
        List<String> list = new ArrayList<>();
//        List<String> list = new LinkedList<>();

        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");

        /*
            E get(int index)
            获取指定下标对应的元素
         */
        //获取第三个元素
        String e = list.get(2);
        System.out.println(e);

        for(int i=0;i<list.size();i++){
    
    
            e = list.get(i);
            System.out.println(e);
        }

        /*
            E set(int index,E e)
            将给定元素设置到指定位置,返回值为该位置原有的元素。
            替换元素操作
         */
        //[one,six,three,four,five]
        String old = list.set(1,"six");
        System.out.println(list);
        System.out.println("被替换的元素是:"+old);
    }
}

Overloaded add() and remove()

package collection;

import java.util.ArrayList;
import java.util.List;

/**
 * List集合提供了一对重载的add,remove方法
 */
public class ListDemo2 {
    
    
    public static void main(String[] args) {
    
    
        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");
        System.out.println(list);
        /*
            void add(int index,E e)
            将给定元素插入到指定位置
         */
        //[one,two,six,three,four,five]
        list.add(2,"six");
        System.out.println(list);

        /*
            E remove(int index)
            删除并返回指定位置上的元素
         */
        //[one,six,three,four,five]
        String e = list.remove(1);
        System.out.println(list);
        System.out.println("被删除的元素:"+e);
    }
}

subList() method

package collection;

import java.util.ArrayList;
import java.util.List;

/**
 *  List subList(int start,int end)
 *  获取当前集合中指定范围内的子集。两个参数为开始与结束的下标(含头不含尾)
 */
public class ListDemo3 {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<10;i++){
    
    
            list.add(i);
        }
        System.out.println(list);
        //获取3-7这部分
        List<Integer> subList = list.subList(3,8);
        System.out.println(subList);
        //将子集每个元素扩大10倍
        for(int i=0;i<subList.size();i++){
    
    
            subList.set(i,subList.get(i) * 10);
        }
        //[30,40,50,60,70]
        System.out.println(subList);
        /*
            对子集元素的操作就是对原集合对应元素的操作
         */
        System.out.println(list);

        //删除list集合中的2-8
        list.subList(2,9).clear();
        System.out.println(list);

    }
}

Conversion of collections and arrays

collection converted to array

Collection provides a method: toArray , which can convert the current collection into an array

package collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 集合转换为数组
 * Collection提供了方法toArray可以将当前集合转换为一个数组
 */
public class CollectionToArrayDemo {
    
    
    public static void main(String[] args) {
    
    
        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");
        System.out.println(list);

//        Object[] array = list.toArray();
        /*
            重载的toArray方法要求传入一个数组,内部会将集合所有元素存入该数组
            后将其返回(前提是该数组长度>=集合的size)。如果给定的数组长度不足,
            则方法内部会自行根据给定数组类型创建一个与集合size一致长度的数组并
            将集合元素存入后返回。
         */
        String[] array = list.toArray(new String[list.size()]);
        System.out.println(array.length);
        System.out.println(Arrays.toString(array));
    }
}

Convert an array to a List collection

The array tool class Arrays provides a static method asList() , which can convert an array into a List collection

package collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 数组转换为List集合
 * 数组的工具类Arrays提供了一个静态方法asList,可以将数组转换为一个List集合。
 */
public class ArrayToListDemo {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "one","two","three","four","five"};
        System.out.println(Arrays.toString(array));
        List<String> list = Arrays.asList(array);
        System.out.println(list);

        list.set(1,"six");
        System.out.println(list);
        //数组跟着改变了。注意:对数组转换的集合进行元素操作就是对原数组对应的操作
        System.out.println(Arrays.toString(array));

        /*
            由于数组是定长的,因此对该集合进行增删元素的操作是不支持的,会抛出
            异常:java.lang.UnsupportedOperationException
         */
//        list.add("seven");

        /*
            若希望对集合进行增删操作,则需要自行创建一个集合,然后将该集合元素
            导入。
         */
//        List<String> list2 = new ArrayList<>();
//        list2.addAll(list);
        /*
            所有的集合都支持一个参数为Collection的构造方法,作用是在创建当前
            集合的同时包含给定集合中的所有元素
         */
        List<String> list2 = new ArrayList<>(list);
        System.out.println("list2:"+list2);
        list2.add("seven");
        System.out.println("list2:"+list2);
    }
}

sorting of collections

java.util.CollectionsClass

Collections is a tool class for collections, which defines many static methods for manipulating collections.

Collections.sort(List list) method

The List collection can be sorted naturally (from small to large)

package collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 集合的排序
 * 集合的工具类:java.util.Collections提供了一个静态方法sort,可以对List集合
 * 进行自然排序
 */
public class SortListDemo1 {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = new ArrayList<>();
        Random random = new Random();
        for(int i=0;i<10;i++){
    
    
            list.add(random.nextInt(100));
        }
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
    }
}

Summarize

Collection

Collection is the top-level interface of all collections, specifying the functions of all collections.

Two common subtypes are:

java.util.Set: non-repeatable collection

java.util.List: Repeatable and ordered collection

Common methods:

boolean add(E e): Add an element to the collection, and return true if the addition is successful

int size(): Returns the number of elements in the current collection

boolean isEmpty(): Determines whether the current collection is empty. Returns true if and only when size=0.

void clear(): Empty the collection

boolean contains(Object o): Determine whether the collection contains the given element

boolean remove(Object o): Removes the given element from the collection, returns true on successful removal.

boolean addAll(Collection c): Add all elements of the given collection to the current collection.

boolean removeAll(Collection c): Deletes the common elements in the current collection and the given collection.

boolean containsAll(Collection c): Determine whether the current collection contains all elements in the given collection.

Iterator iterator(): Get an iterator for traversing the current collection

T[] toArray(T[] t): Convert the current collection to an array. The parameter is the array to convert.

iterator

java.util.Iterator

Iterators are used to traverse collections, and different collections provide an iterator implementation class for traversing their own elements.

The process followed by traversing a collection using an iterator is: Ask -> Get -> Delete. Deletion is not necessary.

common method

boolean hasNext(): Determines whether there are "next" elements in the collection that can be traversed

E next(): Get the next element of the collection

void remove(): Delete the element at the current position of the iterator from the collection (the element obtained by next)

List collection

The list collection has two commonly used implementation classes:

java.util.ArrayList: Internally implemented using an array, the query performance is better.

java.util.LinkedList: Internally implemented using a linked list, the performance of adding and deleting is better, and the performance of adding and deleting at the beginning and the end is the best.

When performance is not critical, ArrayList is usually used.

common method

E get(int index): Get the element corresponding to the specified subscript index

E set(int index, E e): Set the given element to the position specified by index, and the return value is the replaced element at this position.

void add(int index, E e): Insert the given element into the position specified by index

E remove(int index): Delete and return the corresponding element at the subscript index.

List subList(int start, int end): Get the subset between start and end in the current collection. (including head but not tail)

Interchange operations between sets and arrays

To convert a collection to an array, use the collection's toArray method.

Arrays can only be converted to List collections when they are converted to collections, using the Arrays.asList() method.

Guess you like

Origin blog.csdn.net/u013488276/article/details/124855657