Java容器_Set_HashSet源码分析

本文介绍了Java集合框架中的Set接口及其特性,包括无序性和不重复性,并详细解析了HashSet的具体实现方式,如通过HashMap存储元素的过程及源码分析。

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

Set接口是上文介绍的容器的第四个接口,也是最后一个接口,也是实现起来最容易的接口。

(1)Set接口是Collection接口的子接口,Set接口没有提供额外的方法;
(2)Set接口的特性是容器类中的元素是没有顺序的,而且不可以重复;
(3)Set容器可以与数学中“集合”的概念相对应;
(4)JDK API中所提供的Set 容器类有HashSet,TreeSet等。

打开Set接口的源码:

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

    int size();
正如上文所说,没有新定义额外的方法。
打开HashSet源码:
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    // HashSet是使用HashMap实现的
    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

   /**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }


好了,HashSet的实现比较简单,就是HashMap的简单操作,把对象作为Key值赋给Map对象,value使用PRESENT。另外,set没有get方法取值,只能用迭代器遍历查询。

package com.ws.list;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class testiterator {
	public static void main(String[] args) {

		Set set=new HashSet();
		set.add("aaa");
		set.add("aab");	
		
		Iterator iterator=set.iterator();
		while (iterator.hasNext()){
			String str = (String) iterator.next();
			System.out.println(str);
		}
		
		for (Iterator iterator2=set.iterator();iterator2.hasNext();){
			String str = (String) iterator2.next();
			System.out.println(str);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值