天天看点

22010922 List,Set

list和set:

list和set都是collection的子类,而collection是Iterable的子接口。

参考链接:

javaApi中文文档传送门

官方api

注意:

list,set,collection和iterable都是接口。

划重点:

Java中的接口是支持多继承的。 (之前总是习惯性的认为只有类能 继承 结构,接口也是可以 继承 接口的)

一个类只能extends一个父类,但可以implements多个接口。

一个接口则可以同时extends多个接口,却不能implements任何接口。

list介绍(摘自api)

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

list测试代码:

public class ListTest {
    private List<Integer> list;
    private LinkedList<Integer> li = new LinkedList<Integer>();

    @Test
    public void listTest(){
        //测试addAll()方法的前置条件,对第二个参数collection进行初始化
        li.add(4);
        li.add(5);

        list = new ArrayList<>();
        //第一种:指定下标及元素值传参
        list.add(0,1);
        //第二种:在list末尾添加传入的元素值
        list.add(2);
        //第三种:从指定下标开始添加传入colletion的全部元素值
        list.addAll(2,li);
        //可添加null
        list.add(null);
        //可添加多个Null
        list.add(null);
        //添加重复元素值
        list.add(2);
        System.out.println(list);
        System.out.println(list.get(3));
    }
}
           

set介绍(摘自api):

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

set测试代码:

public class SetTest {
    private Set<String> set;
    private LinkedList<String> li = new LinkedList<String>();
    @Test
    public void setTest(){
        //测试addAll()方法的前置条件,对第二个参数collection进行初始化
        li.add("A");
        li.add("1");
        set = new HashSet<>();
        //第一种:add()添加传入的值
        set.add("a");
        //第二种:addAll()添加传入colletion的全部元素值
        set.addAll(li);
        set.add(null);
        System.out.println(set);
    }
}