JAVA学习-List,Set,Map三者的区别

编程知识 更新时间:2023-04-07 23:53:08

List 和 Set 都是单列集合,继承自 Collection接口,Map 是双列集合,是键值对的形式,独立接口。

List 是有序集合,Set 和 Map 都是无序集合,List 集合的元素可以重复,Set 和 Map 的键不能重复,但是 Map 的值可以重复。值得注意的是,如果在 Map 中添加重复的键,那么该键对应的值会覆盖掉原来的值。

测试程序:

import java.util.*;

public class Demo {

    public static void main(String[] args) {
        test_List();
        test_Set();
        test_Map();
    }

    //测试 List 集合
    public static void test_List(){
        //创建 List 集合
        List<Integer> list = new ArrayList<>();
        //添加 10 到 1 的数字
        for(int i = 10; i > 0; --i){
            list.add(i);
        }
        //打印 List 集合的元素
        System.out.print("List集合的元素为: ");
        for(int i: list){
            System.out.print(i + " ");
        }
        System.out.println();
    }

    //测试 Set 集合
    public static void test_Set(){
        //创建 Set 集合
        Set<Integer> set = new HashSet<>();
        //添加 10 到 1 的数字
        for(int i = 10; i > 0; --i){
            set.add(i);
        }
        //打印 Set 集合
        System.out.print("Set集合的元素为: ");
        for(int i: set){
            System.out.print(i + " ");
        }
        System.out.println();
    }

    //测试 Map 集合
    public static void test_Map(){
        //创建 Map 集合
        Map<Integer, Integer> map = new HashMap<>();
        //添加 10 到 1 的数字
        for(int i = 10; i > 0; --i){
            map.put(i, i);
        }
        //打印 Map 集合的键
        System.out.print("Map集合的键为: ");
        for(int i: map.keySet()){
            System.out.print(i + " ");
        }
        System.out.println();
        //打印键 1 的值
        System.out.println("键 1 对应的值为: "+map.get(1));
        //再添加新的键1
        map.put(1, 10);
        System.out.println("添加新的键 1 后对应的值: "+map.get(1));

    }

}

测试结果:

List集合的元素为: 10 9 8 7 6 5 4 3 2 1 
Set集合的元素为: 1 2 3 4 5 6 7 8 9 10 
Map集合的键为: 1 2 3 4 5 6 7 8 9 10 
键 1 对应的值为: 1
添加新的键 1 后对应的值: 10

List 的实现类有 LinkedListArrayListVector。LinkedList 和 ArrayList 的区别可以参考这个:JAVA学习-LinkedList 和 ArrayList 分别的适用场景_什巳的博客-CSDN博客https://blog.csdn/qq_48772498/article/details/122709953

Vector 的底层逻辑和 ArrayList 一样都是动态数组,因此查询的效率高,添加删除的操作效率低,相比 ArrayList,Vector 在单线程中更加安全,但是效率上就会降低。

Set 的实现类有 HashSetTreeSetLinkedHashSet。这三个类都是不允许重复的,但是只有 HashSet 是无序的,TreeSet 和大小顺序有关,LinkedHashHashSet 和插入顺序有关。

Map 的实现类有 HashMapHashTableTreeMapConcurrentHashMapLinkedHashMapweakHashMap。具体介绍可以参考:java中Map有哪些实现类_小泽-CSDN博客_map集合的主要实现类有https://blog.csdn/W_317/article/details/115568584

更多推荐

JAVA学习-List,Set,Map三者的区别

本文发布于:2023-04-07 23:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/386fbacf7309ec43d9eaa064d0a45767.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   List   JAVA   Map   Set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 55212文章数
  • 14阅读数
  • 0评论数