ArrayList和HashSet

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44510615/article/details/102686508

在这里插入图片描述

众所周知:List是接口,ArrayList实现了List接口。那HashSet又是什么玩意?

ArrayList实现了List接口,HashSet实现了Set接口,List和Set都是继承Collection接口。

ArrayList底层是动态数组,HashSet底层是哈希表。

ArrayList存放的是对象的引用,HashSet存放之前检索对象的HashCode,所以当存入对象时要重写hashCode(),如果只是比较对象,只需要重写equals()方法,

ArrayList是有序可重复,HashSet是无序不可重复。

对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

public class UseSetAppMain {
    public static void main(String[] args) {
       
        printCollection(addElementsToCollection(new HashSet()));
        /*
        输出class java.util.HashSet中的元素,共5个
        str3
        str4
        str1
        str2
        str0
         */
        System.out.println("-------------------------");
        printCollection(addElementsToCollection(new ArrayList()));
        /*
        输出class java.util.ArrayList中的元素,共10个
        str0
        str1
        str2
        str3
        str4
        str0
        str1
        str2
        str3
        str4
         */
    }
    // 添加数据
    public static Collection addElementsToCollection(Collection collection) {
        for (int i = 0; i < 10; i++) {
            collection.add("str" + (i % 5));
        }
        return collection;
    }

    public static void printCollection(Collection collection) {
        System.out.println();
        System.out.println("输出" + collection.getClass() + "中的元素,共" + collection.size() + "个");
        try {
            for (Object element : collection) {
                System.out.println(element);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44510615/article/details/102686508