博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java集合-Set源码
阅读量:4204 次
发布时间:2019-05-26

本文共 2067 字,大约阅读时间需要 6 分钟。

简介

Set集合不包含重复的元素,相同的元素只保存一个,不包含相等的两个元素,Set至多只能包含一个NULL元素。Set的实现类都是基于Map来实现的,其中HashSet是通过HashMap来实现的,TreeSet是通过TreeMap实现的。

类图

这里写图片描述

遍历方式

public static void main(String[] args) {
Set
set = new HashSet<>(); set.add("Lions are the most mighty of all animals in Africa."); set.add("Those kids always have so much enthusiasm about studying."); set.add("Calligraphy is the art of beautiful handwriting."); // 迭代器 Iterator
iterator = set.iterator(); while (iterator.hasNext()) {
System.out.println(iterator.next()); } System.out.println("-------------------------------------------"); // 迭代器for循环 for (iterator = set.iterator();iterator.hasNext();){
System.out.println(iterator.next()); } System.out.println("-------------------------------------------"); // 加强型for循环 for (String str : set) {
System.out.println(str); }}

源码

参照JDK1.8版本

Query Operations

//返回集合的大小int size();//集合为空,返回true,否则,返回falseboolean isEmpty();//判断集合是否包含指定对象oboolean contains(Object o);//返回set集合的迭代器Iterator
iterator();//Returns an array containing all of the elements in this set.Object[] toArray();//Returns an array containing all of the elements in this set;
T[] toArray(T[] a);

Modification Operations

//添加一个元素boolean add(E e);//删除一个元素boolean remove(Object o);

Bulk Operations

//Returns true if this set contains all of the elements of the //specified collection. boolean containsAll(Collection
c);//将指定集合的全部元素添加到当前集合中boolean addAll(Collection
c);/*** In other words, removes from this set all of its elements * that are not contained in the specified collection. **/boolean retainAll(Collection
c);/*** Removes from this set all of its elements that are contained* in the specified collection (optional operation). */boolean removeAll(Collection
c);/*** Removes all of the elements from this set (optional operation).*/void clear();

Comparison and hashing

//判断是否相等boolean equals(Object o);//Returns the hash code value for this set. int hashCode();
你可能感兴趣的文章