天天看點

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);
    }
}