java基础类库学习(二.2)Set子接口的实现类

本文深入解析了Set集合的基本概念,探讨了其与Collection接口的区别,详细分析了HashSet的内部实现机制,包括线程安全性、元素顺序及重复性处理,并介绍了HashSet的源码细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Set子接口的实现类:HashSet/LinkedHashSet/TreeSet/EnumSet/SortedSet

Set子接口和Collection父接口源码对比?

1Collection父接口源码

 

public interface Collection<E> extends Iterable<E> {

int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
@since 1.8从jdk8开始接口支持有方法体,必须为static/default修饰
default boolean removeIf(Predicate<? super E> filter) {
    Objects.requireNonNull(filter);
    boolean removed = false;
    final Iterator<E> each = iterator();
    while (each.hasNext()) {
        if (filter.test(each.next())) {
            each.remove();
            removed = true;
        }
    }
    return removed;
}
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
}


2Set子接口源码

 

public interface Set<E> extends Collection<E> {
int size();
boolean isEmpty();
Iterator<E> iterator();
Object[] toArray();
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean retainAll(Collection<?> c);
 
boolean removeAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();

}

3结论

可以发现Set集合基本与Collection集合基本相同,只是Set集合不允许包含重复元素

Set子接口的实现类?HashSet

HashSet的说明

1HashSet实现类没有实现线程同步,不支持多线程安全,需手动实现线程安全

2不能保证元素的顺序,元素不重复

3hashSet源码

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;
public HashSet() {
    map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
public int size() {
    return map.size();
}
public boolean isEmpty() {
    return map.isEmpty();
}
public boolean contains(Object o) {
    return map.containsKey(o);
}
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}
public void clear() {
    map.clear();
}
public Object clone() {
    try {
        HashSet<E> newSet = (HashSet<E>) super.clone();
        newSet.map = (HashMap<E, Object>) map.clone();
        return newSet;
    } catch (CloneNotSupportedException e) {
        throw new InternalError(e);
    }
}
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    // Write out any hidden serialization magic
    s.defaultWriteObject();

    // Write out HashMap capacity and load factor
    s.writeInt(map.capacity());
    s.writeFloat(map.loadFactor());

    // Write out size
    s.writeInt(map.size());

    // Write out all elements in the proper order.
    for (E e : map.keySet())
        s.writeObject(e);
}

}

注意到HashSet中并没有重写Object祖先类的hashCode()和equals()方法,但其父类 AbstractSet<E>实现了,因此用的就是 AbstractSet<E>的这两个方法,

public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
public boolean equals(Object o) {
    if (o == this)
        return true;

    if (!(o instanceof Set))
        return false;
    Collection<?> c = (Collection<?>) o;
    if (c.size() != size())
        return false;
    try {
        return containsAll(c);
    } catch (ClassCastException unused)   {
        return false;
    } catch (NullPointerException unused) {
        return false;
    }
}
public int hashCode() {
    int h = 0;
    Iterator<E> i = iterator();
    while (i.hasNext()) {
        E obj = i.next();
        if (obj != null)
            h += obj.hashCode();
    }
    return h;
}

}

HashSet集合在执行add()操作时,判断两个元素是否相同的依据是euqals()和hashCode()方法,如果euqals()为true并且两个对象的hashCode()也相等,那么这两个元素就是相等的,不会纳入HashSet集合中

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值