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

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博客icon-default.png?t=M0H8https://blog.csdn.net/qq_48772498/article/details/122709953

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

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

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

  • 16
    点赞
  • 80
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什巳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值