java 集合

1.集合框架

2.例子

 

 

 

 

 

package com.ligy.studymvc;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.*;

@SpringBootTest
class StudymvcApplicationTests {
    @Test
    void test3() {
        Set<String> set = new HashSet<>();

        set.add("aa");
        set.add("bb");
        //增强for
        for (String s : set) {
            System.out.println("set:" + s);
        }

    }

    @Test
    void test2() {
        Map<String, Object> map = new HashMap<>();

        //1.put  get
        map.put("a", "aa");
        System.out.println("a:" + map.get("a"));
    }

    @Test
    void test1() {
        //多态
        Collection<String> collection = new ArrayList<>();

        //1.tostring()
        System.out.println(collection);

        //2.add
        collection.add("aa");
        collection.add("aa");
        collection.add("bb");
        collection.add("cc");
        System.out.println(collection);

        //3.remove
        collection.remove("aa");
        System.out.println(collection);

        //4.clear
        //collection.clear();
        //System.out.println(collection);

        //5.isEmpty
        if (collection.isEmpty()) {
            System.out.println("空");
        } else {
            System.out.println("非空");
        }

        //6.contains
        if (collection.contains("bb")) {
            System.out.println("包含:bb");
        } else {
            System.out.println("不包含:bb");
        }

        //7.size()
        System.out.println("size:" + collection.size());

        //8.get
        System.out.println("0:" + ((ArrayList<String>) collection).get(0));

        //9.迭代器。一个个读取,直到最后1个,
        Iterator<String> iterator = collection.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }


    }

}

 

package com.ligy.studymvc;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

@SpringBootTest
public class ListTest {
    @Test
    void test1() {
        //List 集合,几个子类

        //1.ArrayList
        //查询快,插入/更新/删除慢
        List<String> l1 = new ArrayList<>();
        l1.add("aaa");
        System.out.println(l1.get(0));

        //2.LinkedList
        //查询慢,插入/更新/删除快
        List<String> l2 = new LinkedList<>();
        l2.add("bbb");
        l2.add("bbb22222");
        String first = ((LinkedList<String>) l2).getFirst();
        System.out.println(l2.get(0));
        System.out.println(first);

        //3.Vector
        //单线程,慢,被ArrayList淘汰。。。
        List<String> l3 = new Vector<>();
        l3.add("ccc");
        ((Vector<String>) l3).addElement("ccc222");
        System.out.println(l3.get(0));
        System.out.println(l3.get(1));
    }
}

 

posted on 2022-01-01 09:20  biind  阅读(40)  评论(0编辑  收藏  举报