Set接口HashSet实现类

java.util.Set接口 extends Collection接口

Set特点:
1、不允许有重复的元素
2、没有索引,没有带索引的方法,也不能使用普通的for遍历

java.util.HashSet集合 implements Set接口

Set接口的一个实现类
HashSet特点:
1、没有重复的元素
2、没有索引,没有带索引的方法,也不能使用普通的for遍历
3、是一个无序的集合,存储和取出的顺序有可能不一致
4、底层是一个哈希表结构(查找快)

public class Demo01Set {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        set.add(3);
        set.add(3);
        set.add(2);
        set.add(12);
        set.add(22);
        set.add(13);// 添加
        set.add(222);
        System.out.println(set.size());
        Iterator<Integer> it = set.iterator();
        while(it.hasNext()) {// while迭代器遍历
            Integer next = it.next();
            System.out.println(next);

        }

        for(Integer next: set) {// for each遍历
            System.out.println(next);
        }
    }
}

哈希值

Object类有一个hashCode方法,返回对象的哈希值,一个十进制的值

Student stu = new Student();
int hashcode = stu.hashCode();

猜你喜欢

转载自www.cnblogs.com/zhuobo/p/10625301.html
今日推荐